I have an js object
var myClass = Class.extend({
_innerArr: [],
add: function( id, url ){
this._innerArr.push([id, url]);
},
delete: function( id ){
$( this._innerArr ).each(function( index ){
if ( $( this )[0]==id ){
this._innerArr.splice( index, 1); // Doesn't work!!! Uncaught TypeError: Cannot call method 'splice' of undefined
}
});
}
});
But, if code change on:
var globalArr;
var myClass = Class.extend({
_innerArr: [],
add: function( id, url ){
this._innerArr.push([id, url]);
},
delete: function( id ){
globalArr = this._innerArr;
$( this._innerArr ).each(function( index ){
if ( $( this )[0]==id ){
globalArr.splice( index, 1); // Work!!!
}
});
}
});
why this._innerArr not work? I don't want using adding variable in my project. Thinks, other way is...
2 Answers 2
When using jQuery's .each() method, the function gets called with this as the current value of the array. You're using that when doing $( this )[0]. ($( this )[0] might be unnecessary btw.)
You don't need to create a global variable for this, but you might as well set a scoped variable in the delete function.
Alternately, you can just use a for loop instead of jQuery's each(). That's also a little faster.
Comments
The reason why this happens is because the scope of this changes inside of the .each() callback; this is a pretty well known phenomena and typically involves saving this in another variable outside of the function call.
Instead of splicing things yourself, you could make use of jQuery.grep():
this._innerArr = $.grep(this._innerArr, function(element) {
return element[0] != id;
});
eachvarinto thedeletefunction is enough, you don't need it completely global.innerArr