I trying to add a getter method to String so that it can be called like so:
'make me bold'.bold
Without parentheses. Here is how I'm trying to define the function, as described here .
String.prototype.defineProperty(window, 'bold', { get: function (input) {
return ('</b>'+input+'</b>');
}});
It says that defineProperty isn't a function though. Doesn't work if i take out prototype either. It looks possible to do with 'String.prototype. defineGetter ' but says it's deprecated:
String.prototype.__defineGetter__('bold', function (input) {
return ('</b>'+this+'</b>');
});
You need to use Object.defineProperty:
Object.defineProperty(String.prototype, 'bold', { get: function (input) {
return ('</b>'+this+'</b>');
}});
You can add that function to the prototype instead:
String.prototype.bold = function () { return ('</b>' + this + '</b>'); }; console.log('make me bold'.bold()) console.log('Ele from SO'.bold())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.