JavaScript - 在内部函数中引用“this” [英] JavaScript - referencing 'this' in an inner function

查看:125
本文介绍了JavaScript - 在内部函数中引用“this”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

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

它不工作,因为显然 / code>没有绑定到闭包的执行上下文中。我已经能够通过引入另一个变量来工作:

It doesn't work, since apparently this is not bound into the closure's execution context. I've been able to work it around by introducing another variable:

var _this = this;

这在匿名函数中工作。但对我来说看起来很丑陋。有没有一些好的方法来处理这个?

And this works inside the anonymous function. But looks quite ugly to me. Is there some nice way to handle this?

推荐答案

这可能看起来像你的丑陋的解决方案,作为使用 bind() method 更改上下文),但这是我知道的最佳解决方案。

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.

这篇关于JavaScript - 在内部函数中引用“this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆