JavaScript - referencing 'this' in an inner function

霸气de小男生 提交于 2019-12-02 03:58:23

This may look like the ugly solution for you and there are some walkarounds (such as using bind() method to change the context), but this is the best solution I know of.

Alternatively you can change it to:

var self = this;

or give it more meaningful name, but it would be better (in this case) not to change the context, as you may need it some day.

You can make usage of Function.prototype.bind for that:

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

Now the parent context variable is also bound to the anonymous function.

the this syntax usually refers to the object, not a function. In your case, this refers to MyClass.

If you're using the variable in the object, you probably forgot to define x in MyClass.

If you're using the variable within the function ONLY I'd define my variables using the var syntax. Variables defined within a function are destroyed when a function ends.

MyClass.prototype.my_func = function () {
    var x = 10;

    $.ajax({
        // ...
        success: function (data) {
            alert(x);
        }
    });
}
James Sumners

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."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!