0

I want to write a log method for String that can print the string, but it not work on the correct way

String.prototype.log = () => console.log(this.toString())
'Print Me'.log()  // [object Window]

I want to print Print Me, not [object Window], how can I make it work

Vic
  • 105
  • 1
  • 9

2 Answers2

1

Oh yes! It does. The error is that this doesn't point to the string in an arrow function:

String.prototype.log = function() {
  console.log(this.toString())
}

'Print Me'.log();

You can see that it works when you do it using a regular function. You need to read more about lexical scoping of arrow functions.

31piy
  • 23,323
  • 6
  • 47
  • 67
1

this in arrow functions belongs to the enclosing context. You shouldn't be using arrow function here since you will need to access the string object.

Make it

String.prototype.log = function() { console.log(this.toString()) }
gurvinder372
  • 66,980
  • 10
  • 72
  • 94