Can anyone explain the following to me please.
Case 1:
function MyObj () {
this.myArray = new Array();
for(var i = 0; i<5; i++){
this.myArray.push(i);
console.log("add to array:" + i);
}
}
which works as I expected. this.myArray has 0,1,2,3,4.
Case 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);
});
}
I got complains from Firebug “this.myArray is undefined.”
Thanks.
In your second example, you’re passing a function to
$.each, which means that$.eachwill invoke that function. Therefore, inside that function,thiswill refer to what$.eachassigns it to be.Normally, it would be a reference to
$.eachin itself, but jQuery invokes the callbacks using.callwhich allows manual specification of the context to use. In the case of$.each,thisis set to always refer to the current object of the iteration.There are ways to work around this, you could for instance do something like this: