javascript - Questions about context, that is, what this points to?
某草草
某草草 2017-07-05 10:56:18
0
5
917

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!

某草草
某草草

reply all(5)
大家讲道理

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 this points to who.

The pointing of

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.

Ty80

/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 = {

    outer: function () {
        // 此时this指向test对象
        var that=this
        console.log(this);

        function inner() {
            // 此时this指向window
            console.log(that);
        }
        inner();
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template