js novice, if you encounter problems, please write the code first
var name = "John";
var myObject = function() {
return {
getName: function() {
return this.name;
}
}
}();
alert(myObject.getName());
The output result is undefined
My question is 1. Is the getName
inside return
an anonymous function? What I understand now is Anonymous function, then this this
should point to the global world, right? It’s window
Then why is it not outputting john
2. What makes me even more confused is that when I was debugging, I walked step by step and reached this.name
, this
points to Object
and when undefined
is output, the this
I am monitoring there becomes window
, this.name
has also become john
, I don’t quite understand, please help me!
This problem needs to be looked at step by step. First, myObject is an object. There is a property on it called getName, and the value is an anonymous function,
alert(myObject.getName());
. It is this object that is calling this method. All of this At this time, this is undefined.Extend it again, look at the code below
The object.getName() method returns an anonymous function. The execution environment is the global scope. This points to the execution scope based on the function, so it is window. At this time, window.name is John.
If we want to return lucy, we need to do it by creating an arrow function or closure.
The this object in the arrow function body is the object where it is defined, not the object where it is used.
As for the problem of debugging this point change, it is because the original scope of the anonymous function is window, but when it is executed, myObject calls it, so this points to myObject at that moment.
getName
’sthis
refers tomyObject
, becausegetName
is directly called bymyObject
, so this here refers to ————The object that calls the function
myObject.getName()
Usually whoever calls a function will point to who this function points to