0

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>');
});
stackers
  • 2,701
  • 4
  • 34
  • 66

2 Answers2

2

You need to use Object.defineProperty:

Object.defineProperty(String.prototype, 'bold', { get: function (input) {
  return ('</b>'+this+'</b>');
}});
Axnyff
  • 9,213
  • 4
  • 33
  • 37
0

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())
Ele
  • 33,468
  • 7
  • 37
  • 75