如何将getter方法添加到内置的String对象中?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将getter方法添加到内置的String对象中?相关的知识,希望对你有一定的参考价值。
我试图向String添加一个getter方法,以便可以像这样调用它:
'make me bold'.bold
没有括号。以下是我试图定义函数的方法,如here所述。
String.prototype.defineProperty(window, 'bold', { get: function (input) {
return ('</b>'+input+'</b>');
}});
它说defineProperty不是一个功能。如果我拿出原型也行不通。看起来可能与'String.prototype.defineGetter'有关,但表示它已被弃用:
String.prototype.__defineGetter__('bold', function (input) {
return ('</b>'+this+'</b>');
});
答案
您需要使用Object.defineProperty:
Object.defineProperty(String.prototype, 'bold', { get: function (input) {
return ('</b>'+this+'</b>');
}});
另一答案
您可以将该函数添加到原型中:
String.prototype.bold = function () {
return ('</b>' + this + '</b>');
};
console.log('make me bold'.bold())
console.log('Ele from SO'.bold())
以上是关于如何将getter方法添加到内置的String对象中?的主要内容,如果未能解决你的问题,请参考以下文章