JavaScript 和 jQuery,匿名函数内的 "this"

标签 javascript closures this anonymous-function

我有这个代码:

PageList: function(url, index, classes){
    this.url = url;
    this.index = index;
    ...
};

PageList.prototype.toHTML = function(){
    var div = $('<div class="container"></div>');
    var p = $('<p></p>');
    var link = $('<a></a>');
    $.each(this.elements, function(index, array_value){
          console.log(this.url);
          ...
    }
}

它按预期工作。

问题是 console.log(this.url) 正在打印 undefined,所以我将代码重写为如下所示:

PageList.prototype.toHTML = function(){
    var div = $('<div class="container"></div>');
    var p = $('<p></p>');
    var link = $('<a></a>');
    var instance = this;
    $.each(this.elements, function(index, array_value){
               console.log(instance.url);
        }
}

我知道问题出在闭包上,它没有将 this 作为实例的值,但据我所知,在一个函数中引用了 this没有绑定(bind)到它的实例必须引用窗口对象,而不是 undefined,至少在许多浏览器上都是这种情况。

那么我的代码到底发生了什么。

注意:我正在使用 jQuery 并且 this.elements 已经定义。

编辑:现在我发现 $.each 是一个非实例函数,所以我的回调是从 $.each 调用的,但它必须是 windowthis的引用,还在想。

最佳答案

根据jQuery docs对于 $.each:

The value [of the current element] can also be accessed through the this keyword...

在 JavaScript 中,当您将回调函数传递给 higher-order function 时(在这种情况下,$.each),高阶函数可以决定回调运行时 this 的值。您无法控制此行为——只是不要使用 this(例如,通过在您的示例中使用像 instance 这样的引用或通过闭包)。

查看上下文设置函数 Function.callFunction.apply了解像 $.each 这样的高阶函数如何设置回调的 this 上下文。阅读这些 MDN 页面后,您可能会清楚一些事情。

这是一个简单的例子:

Array.prototype.forEachWithContext(callback, this_in_callback) {
    for(var i = 0; i < this.length; ++i) {
        callback.call(this_in_callback, i, this[i]);
    }
}

并使用它:

PageList.prototype.toHTML = function(){
    //...
    this.elements.forEachWithCallback(function(index, array_value){ ... }, this);
}

我的示例 Array.forEachWithContext 类似于 Array.forEach。但是,它需要一个回调 第二个参数,在执行每个回调期间用作 this 的值。

关于JavaScript 和 jQuery,匿名函数内的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10393429/

相关文章:

c++ - 如何在对象成员函数中重新分配 `this` 指针?

java - 子类使用 "this"调用父类(super class)方法

javascript - Websocket 客户端到服务器发送 Float32Array - 我做错了什么

带有许多参数的javascript ajax发送到php文件

javascript - 如何在 javascript onclick 函数中传递带有/作为参数的变量

arrays - Rust 中的闭包数组

javascript - IE 版本检查停止工作

ios - Swift 中闭包中的 $0 代表什么?

javascript - Node.js:异步代码 + js 闭包的问题

c++ - QLocalServer - 初学者帮助