【发布时间】:2012-05-10 17:28:16
【问题描述】:
我有这个代码:
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引用 window 对象,而不是 undefined,至少在许多浏览器上都是这样。
那么我的代码到底发生了什么。
注意:我使用的是 jQuery,this.elements 已经定义。
编辑:现在我发现$.each 是一个非实例函数,所以我的回调是从$.each 调用的,但它必须是window 对this 的引用,还在考虑它。
【问题讨论】:
-
欢迎来到 JavaScript 作用域的世界。
标签: javascript closures this anonymous-function