2011-11-18 64 views
0

任何人都可以向我解释以下给我。JavaScript和Jquery循环数组中的JavaScript构造函数

案例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); 
    }); 
} 

我从萤火虫抱怨 “this.myArray是不确定的。”

谢谢。

+1

这是因为范围。情况2中的“this”是数组中的实际数字。它引用了[0,1,2,3,4]。你只需要创建一个var并且不要使用'this'。所以你可以做一些类似'function(){myres.push(this);' – Matt

回答

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); 
}); 
+0

谢谢,明白了。有没有办法可以将情况2中的值推入myArray? – user200340

+0

太棒了,接受。 – user200340

0

this在JavaScript是“绑定”到当前对象。在第一个例子中,它是全局作用域,在第二个函数参数中(我的意思是0,1等),其中未定义myArray。阅读thisthis 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); 
    }); 
} 
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(); 

http://jsfiddle.net/KmxJC/

0

在。每个功能,this是指被检查的元素,因此实际的0,1,2 ......等。此外,this将永远是一个对象,即使原来是一个数字(在你的情况下)或一个字符串或其他任何东西。

有关更多信息,请参阅http://api.jquery.com/jQuery.each/

编辑:我认为要解决你的问题,你可以简单地做一个变量arr这将是可以从.each代码中访问。也就是说,如果每个都不在全球范围内,我不确定。

var arr = new Array(); 

$.each([0,1,2,3,4],function(i,v){ 
    arr.push(i); 
    console.log("add to array:" + v); 
}); 
0

其实当你使用jQuery函数.each时,这意味着不是myObjobj,而是数组的元素。你应该使用这样的代码。

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); 
}); 
}