JavaScript classes method binding | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

27th Jun 2019, 9:39 PM
Dimitris K
Dimitris K - avatar
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.
30th Jun 2019, 9:34 AM
Jack McCarthy
Jack McCarthy - avatar
+ 1
Thank you so much for answering to my question!
30th Jun 2019, 2:16 PM
Dimitris K
Dimitris K - avatar