Directly upload the code:
var test = {
outer: function () {
// 此时this指向test对象
console.log(this);
function inner() {
// 此时this指向window
console.log(this);
}
inner();
}
}
What is the reason why this points to different points in the above code?
It’s all clear to me now, please give me some answers!
Throwing out function borrowing and constructor functions, there are only two types left, one is an ordinary function and the other is an object method.
Object methods point to the object, ordinary functions point to the global
Whoever calls this function, then
The pointing ofthis
points to who.this
is only related to how you call this function. For example, if you say that the firstthis
points totest
, this is not necessarily true. There are ways to change the pointing ofthis
. Only when you runtest.outer()
will the firstthis
point totest
./a/11...
This is a closure problem. When an object is assigned attributes through object literals, including a function method, this function method has a console output, and then a function is declared in this function, a closure problem is formed. Closure Under normal circumstances, this points to the window. In special circumstances, you can change the value of this. You can read an article I wrote about packet closure. You will gain insights on mobile phone inconvenience. You can read my profile
In fact, it’s wrong to answer anonymously! The function defined inside the function in the object cannot directly obtain the upper-level environment variable, let alone the this inside. You must define a variable for it, such as var that=this; in this way, you can get the upper-level this object;
var test = {