JavaScript - referencing 'this' in an inner function

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

Consider the following code:

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


        
4条回答
  •  [愿得一人]
    2021-01-23 15:42

    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.

提交回复
热议问题