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!
大家讲道理2017-07-05 10:58:18
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
曾经蜡笔没有小新2017-07-05 10:58:18
Whoever calls this function, then this
points to who.
this
is only related to how you call this function. For example, if you say that the first this
points to test
, this is not necessarily true. There are ways to change the pointing of this
. Only when you run test.outer()
will the first this
point to test
.
女神的闺蜜爱上我2017-07-05 10:58:18
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
巴扎黑2017-07-05 10:58:18
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 = {
outer: function () {
// 此时this指向test对象
var that=this
console.log(this);
function inner() {
// 此时this指向window
console.log(that);
}
inner();
}
}