javascript - 为什么这个闭包不能访问 'this' 关键字? -jQuery

标签 javascript jquery closures this

我是闭包(和一般的 Javscript)的初学者,我找不到关于这段代码中发生的事情的令人满意的解释:

function myObject(){
    this.myHello = "hello";
    this.myMethod = do_stuff;
}

function do_stuff(){
    var myThis = this;
    $.get('http://example.com', function(){
        alert(this.myHello);
        alert(myThis.myHello);
    });
}

var obj = new myObject;
obj.myMethod();

它会提示“undefined”然后是“hello”。显然这不应该是特定于 jQuery 的,但这是我能想到的原始代码的最简单形式。 do_stuff() 中的闭包可以访问该范围内的变量,但显然此规则不适用于 this 关键字。

问题:

当闭包传递到 do_stuff() 范围之外时,this 会发生什么(在本例中为 $.get()) ? myThis 是否包含 this 的副本或对它的引用?在闭包中使用 this 通常不是一个好主意吗?

非常感谢任何回复。

最佳答案

What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?

每个函数都有自己的执行上下文,this 关键字检索当前上下文的值。

doStuff 标识符和 obj.myMethod 属性指的是同一个函数对象,但是由于您将它作为对象的属性调用 (obj .myMethod();),该函数中的 this 值将引用 obj

当 Ajax 请求成功时,jQuery 将调用第二个函数(启动一个新的执行上下文),并且它将使用一个包含用于请求的设置的对象作为 this 的值那个回调。

Does myThis contain a copy of this or a reference to it?

myThis 标识符将包含对对象的引用,该对象也被外部作用域上的 this 值引用。

Is it generally not a good idea to use this in closures?

如果您了解如何隐式处理 this 值,我看不出有任何问题...

由于您使用的是 jQuery,因此您可能需要检查 jQuery.proxy方法,是一种实用方法,可用于保留函数的上下文,例如:

function myObject(){
    this.myHello = "hello";
    this.myMethod = do_stuff;
}

function do_stuff(){
    $.get('http://example.com', jQuery.proxy(function(){
        alert(this.myHello);
    }, this)); // we are binding the outer this value as the this value inside
}

var obj = new myObject;
obj.myMethod();

另见:

关于javascript - 为什么这个闭包不能访问 'this' 关键字? -jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3323189/

相关文章:

javascript - jQuery 选择器不适用于数据表

javascript - AES-KW 的 unwrapKey 函数在 IE11 中不起作用

jquery - 具有现有表单的fineuploader

javascript - 鼠标悬停时 Jquery Inewsticker 暂停

javascript - Windows 8 应用程序是否在符合标准的 JavaScript、HTML5 和 CSS3 上运行?

javascript - 价格为零时隐藏价格

javascript - 如何使同一按钮的不同实例独立响应鼠标事件

closures - 通用 fn、 channel 和线程生成

php - 在 PHP 中序列化或散列闭包

groovy - Groovy 中带类型参数的闭包