search

Home  >  Q&A  >  body text

javascript - Questions about context, that is, what this points to?

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!

某草草某草草2706 days ago896

reply all(5)I'll reply

  • 大家讲道理

    大家讲道理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

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:58:18

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 10:58:18

    /a/11...

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我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

    reply
    0
  • 巴扎黑

    巴扎黑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();
        }
    }

    reply
    0
  • Cancelreply