0

I'm rather beginning in JavaScript/jQuery, so pardon my question if it feels too basic.

I have class with two (or more) methods, one calls another inside it inside jQuery $.each() loop.

class X {
    method_a (array){
        $.each(array, function(index, item){
            this.method_b(item);
        });
    }
    method_b (item) {
        // do something with item
    }
}

But this throws TypeError, that method_b is not a function, since this refers to the item instead of this object. Is there any other way properly call this inside a jQuery $.each() or the only way is to make a variable let obj = this; and call it a day?

Am I missing something? Maybe something with methods' declaration? Any help would be appreciated.

Eric Luther
  • 117
  • 1
  • 10
  • 1
    Use an arrow function instead, `(index, item) => {` – CertainPerformance Oct 16 '19 at 10:48
  • Arrow function is a no-go for me as it does not work on IE :-( Damn IE... – Eric Luther Oct 16 '19 at 10:50
  • Then use Babel to transpile your code down to ES5 automatically - don't let obsolete browsers cripple the readability of your code – CertainPerformance Oct 16 '19 at 10:52
  • oldschool way of doing it: `class X { method_a (array){ var that = this; $.each(array, function(index, item){ that.method_b(item); }); } method_b (item) { // do something with item } }` – Lumpenstein Oct 16 '19 at 10:53
  • @Lumpenstein that was my first idea, but it looks terrible, so I'm trying to avoid it, hence asking this question ;-) – Eric Luther Oct 16 '19 at 10:56
  • the newer way of doing it is to use the .bind/.call./apply functions to pass the 'this' context, but not sure if this is supported with jQuery (haven't used it for 2 years) – Lumpenstein Oct 16 '19 at 10:57
  • @Eric see answer [here](https://stackoverflow.com/questions/9244018/is-it-possible-for-jquery-each-function-not-to-clobber-the-this-variable) for another way – Lumpenstein Oct 16 '19 at 10:59

0 Answers0