+ 1
JavaScript classes method binding
Today I had a lesson on method binding, and how the âthisâ keyword cannot be passed to another reference by just pointing to a method reference that returns âthisâ. Can anyone please explain to me why that happens? If possible, on memory, and not necessarily in JavaScript. Thanks in advance! https://code.sololearn.com/WF66sS44HPNc/?ref=app
2 Answers
+ 2
Great question!
So, the "this" keyword in JavaScript always refers to the current object containing the function. In the example that you linked to, the reason you are getting that error is because you are calling the function outside of any object! This happens when you create the function pointer "getName" and assign it to obj.getName. When you call the getName() function inside the console.log statement, the function attempts to resolve the value of "this". When you were calling obj.getName(), it could be infered that "this" referred to "obj", so when you try to return this.name, that gets substituted for obj.name. Luckily, obj has a member called name, which is what is returned. However, when you create the getName function pointer outside of the scope of obj, the meaning of "this" changes. Now, when you call "this.name", the interperator no longer knows what "this" refers to, since getName has a global scope. Therefore, the interperator throws an error since it can not figure out what "this.name" could be referring to.
+ 1
Thank you so much for answering to my question!