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

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

问题描述

考虑以下代码:

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

它不起作用,因为显然 this 没有绑定到闭包的执行上下文中.我已经能够通过引入另一个变量来解决这个问题:

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() 方法 更改上下文),但这是我所知道的最佳解决方案.

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天全站免登陆