var self = this?

后端 未结 8 1424
失恋的感觉
失恋的感觉 2020-11-22 09:10

Using instance methods as callbacks for event handlers changes the scope of this from \"My instance\" to \"Whatever just called the callback\"

8条回答
  •  遇见更好的自我
    2020-11-22 09:40

    This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

    var abc = 1; // we want to use this variable in embedded functions
    
    function xyz(){
      console.log(abc); // it is available here!
      function qwe(){
        console.log(abc); // it is available here too!
      }
      ...
    };
    

    This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

    // we want to use "this" variable in embedded functions
    
    function xyz(){
      // "this" is different here!
      console.log(this); // not what we wanted!
      function qwe(){
        // "this" is different here too!
        console.log(this); // not what we wanted!
      }
      ...
    };
    

    What can we do? Assign it to some variable and use it through the alias:

    var abc = this; // we want to use this variable in embedded functions
    
    function xyz(){
      // "this" is different here! --- but we don't care!
      console.log(abc); // now it is the right object!
      function qwe(){
        // "this" is different here too! --- but we don't care!
        console.log(abc); // it is the right object here too!
      }
      ...
    };
    

    this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.

提交回复
热议问题