JavaScript - referencing 'this' in an inner function

后端 未结 4 1540
小鲜肉
小鲜肉 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 16:04

    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.

提交回复
热议问题