I got confused, because I always thought that this
refers to the object owner, or the owner of the function, or method, but according to w3schools, this
refers to the caller of the function, and the example they provided really does shows that.
function myFunc(name) {
this.name = name;
this.showName = function() {
console.log(this)
}
}
window.addEventListener('load', myObj.showName)
Why does this
here refer to the caller, in this case, the window object?
When invoked as a method, it refers to the object owner:
myObj.showName()
In here, it refers to the owner of the function, which is the myObj instance.
So, when I invoked the function as a call back, am I not invoking again the object method? How is it different? Isn't the owner of the function still the object myObj even when invoked as a call back? Does the object owner change?
Is there any difference between this
inside the method, and this inside the constructor, i.e. this
in here: this.name = name
, and this
inside the method: this.showName() = function() { console.log(this) }
?
This explanation does not explain why this
refers to the caller when used as a callback, or whether definitely this
inside a constructor refers to the object owner or the caller.