我有这个代码:
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
调用的,但它必须是 window
对this
的引用,还在想。
最佳答案
根据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.call
和 Function.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/