Why wasn’t Binding made of this in that capacity.
Perhaps the best way to see the this be like any argument: it has to be initialized with some value.
When you invoke a method (invokes a function through an object), the JS itself initializes the this with a reference to the object:
var obj = {
val: 10,
logValue() {
console.log(this.val);
}
}
obj.logValue();
It works, right? The this was initialized with a reference to obj, and therefore this.val is the same as obj.val.
Now what happens if we untie the function of obj?
var obj = {
val: 10,
logValue() {
console.log(this.val);
}
}
var func = obj.logValue;
func();
No longer works. this no longer refers to obj, refers to window, because it was not made the function Binding with obj.
In note, Binding can be done manually as well:
var obj = {
val: 10,
logValue() {
console.log(this.val);
}
}
var func = obj.logValue;
func.bind(obj)();
That’s basically what happens when you do obj.logValue(), Binding is automatically made for you.
If you know Python, it is similar to how the first argument is automatically initialized with a reference to the object, when you invoke a function through an object.
https://i.stack.Imgur.com/oSp4t.jpg
– hkotsubo
is the famous scope ...
– novic
good reading: https://imasters.com.br/development/escopos-em-javascript
– novic