0

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...

user3454794
  • 15
  • 1
  • 5

2 Answers2

3

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.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
0

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;
});
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309