+ 6

How to access caller object inside the method declared as prototype in JavaScript?

I have this code: https://code.sololearn.com/WxPrU6BqHUy8/#html In which I'm playing with the prototype property of any object (in my case, it is String object). So, when I try to declare a method named "Length" which does nothing, but returns length property; then I sometime got 0 (in sololearn/Play) and sometime an error: "this is undefined" in MDN Demo. I'm having trouble in passing the String object "str" inside its own Length method. But, in JavaScript, `this` is window object, so that's getting passed into the method. How do I resolve this? PS: I've tried using .call and .apply method, but it didn't worked out :/

28th May 2019, 4:14 PM
777
777 - avatar
4 Respostas
+ 12
Instead of using the ES6 arrow function, just use the function keyword: String.prototype.Length = function() { return this.length; } The problem is ES6 arrow functions bind the [this] keyword to the parent context of the arrow function at the time of assignment. When String.prototype.Length = () => {...} is called, the parent context is actually [window], not [String]. DISCLAIMER: This is how I understand it from memory at the moment. I may need to confirm my handle on this explanation. 😉
28th May 2019, 4:27 PM
David Carroll
David Carroll - avatar
+ 10
Follow up : I've put together a quick test script to validate my explanation regarding the sticky binding behavior of ES6 arrow functions. https://code.sololearn.com/WPEe16x60oV1/?ref=app I hope my console log notes make sense.
28th May 2019, 5:27 PM
David Carroll
David Carroll - avatar
+ 8
You should not use arrow function for prototype function. Try this String.prototype.Length = function () { return this.length; }; In prototype function, 'this' is the calling object, not window object.
28th May 2019, 4:25 PM
Calviղ
Calviղ - avatar
+ 5
Thanks David and Calvin. I got my problem solved \o/
28th May 2019, 4:42 PM
777
777 - avatar