Search code examples
javascriptfunctionmethodsbuilt-in

How do I add a getter method to the built in String object?


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>');
});

Solution

  • You need to use Object.defineProperty:

    Object.defineProperty(String.prototype, 'bold', { get: function (input) {
      return ('</b>'+this+'</b>');
    }});