JavaScript - referencing 'this' in an inner function

后端 未结 4 1500
小鲜肉
小鲜肉 2021-01-23 15:04

Consider the following code:

MyClass.prototype.my_func = function () {
    this.x = 10;
    $.ajax({
        // ...
        success: function (data) {
                   


        
4条回答
  •  猫巷女王i
    2021-01-23 16:03

    The closure will have access to all objects defined in its parent's context. So if we have:

    function() {
      var x = 10;
    }
    

    Then this is valid:

    function() {
      var x = 10;
    
      (function() {
        alert(2*x); // 20
      }())
    }
    

    Therefore, when you define var _this = this you have merely defined a new variable in the parent's context that is available within the closure. See question #4371333 for more information on this "pattern."

提交回复
热议问题