任何人都可以向我解释以下内容。
案例1:
function MyObj () {
this.myArray = new Array();
for(var i = 0; i<5; i++){
this.myArray.push(i);
console.log("add to array:" + i);
}
}
按预期工作。 this.myArray有0,1,2,3,4。
案例2:
function MyObj () {
this.myArray = new Array();
$.each([0,1,2,3,4],function(i,v){
this.myArray.push(i);
console.log("add to array:" + v);
});
}
我从Firebug得到了抱怨“这个。我的阵容未定义。”
感谢。
答案 0 :(得分:4)
在第二个示例中,您将函数传递给$.each
,这意味着$.each
将调用该函数。因此,在该函数中,this
将引用$.each
赋予它的内容。
通常,它本身就是$.each
的引用,但jQuery使用.call
调用回调,允许手动指定要使用的上下文。在$.each
的情况下,this
被设置为始终引用迭代的当前对象。
有很多方法可以解决这个问题,例如你可以这样做:
var context = this;
$.each([0,1,2,3,4],function(i,v){
context.myArray.push(i);
console.log("add to array:" + v);
});
答案 1 :(得分:0)
this
与当前对象“绑定”。在第一个例子中,它是全局范围,在第二个函数参数中(我的意思是0,1等等),其中未定义myArray。阅读this和this explanation。
在您的情况下,您可以这样做:
function MyObj () {
this.myArray = new Array();
var that = this;
$.each([0,1,2,3,4], function(i,v){
this.myArray.push(i);
console.log("add to array:" + v);
});
}
答案 2 :(得分:0)
this
不在MyObj()
函数的正确范围内,而是引用$.each()
循环的当前迭代。改为:
function MyObj() {
var $this = this;
this.myArray = new Array();
$.each([0,1,2,3,4],function(i,v){
$this.myArray.push(i);
console.log("add to array:" + v);
});
console.log(this.myArray);
}
MyObj();
答案 3 :(得分:0)
在.each函数中,this
指的是被检查的元素,因此实际的是0,1,2 ......等。此外,this
将始终是一个对象,即使原始数字是一个数字(在您的情况下)或字符串或其他任何内容。
有关详细信息,请参阅http://api.jquery.com/jQuery.each/。
编辑:我认为要解决您的问题,您可以简单地创建一个变量arr
,该变量可以从.each代码中访问。也就是说,如果.each不在全球范围内,我不确定。
var arr = new Array();
$.each([0,1,2,3,4],function(i,v){
arr.push(i);
console.log("add to array:" + v);
});
答案 4 :(得分:0)
实际上当你使用jQuery函数.each时,这意味着不是myObj obj,而是数组的元素。你应该使用这样的代码。
function MyObj () {
this.myArray = new Array();
var obj = this;
$.each([0,1,2,3,4],function(i,v){
obj.myArray.push(i);
console.log("add to array:" + v);
});
}