THIS object in conflict between jQuery and ECMA6 class

1

How do I resolve the conflict between this of a jQuery loop performed within a method of a class in javascript (ECMA6)?

Example, metodoUm loops using jQuery and for each iteration of the loop, calls metodoDois passing the interaction object as a parameter, so there are two this , one referring to class Teste and another reference to the element found in each iteration of the .each method.

class Teste{
    metodoUm(){
        $('input').each(function () {
            // $(this) adicionado para referenciar o jQuery
            this.metodoDois($(this)); 
        });
    }

    metodoDois(t){
        console.log(t);
    }
}
teste = new Teste();
teste.metodoUm();

Error presented:

TypeError: this.metodoDois is not a function(...).

How to solve, or get around, this conflict?

Thanks in advance for your help.

    
asked by anonymous 06.08.2016 / 01:59

3 answers

4

Since you are already using ES6, you can use Arrow Functions to preserve reference of this and solve this problem.

Example:

$('input').each((i, elemento) => {
    this.metodoDois($(elemento)); 
});

The above code would sub-replace the code from within your metodoUm() function.

About Arrow Functions

Arrow Functions is a novelty of ES6 that has the advantages of a shorter syntax than the conventional function declaration, as well as preserving the value of this (as opposed to the default format).

function () {
    // declaração de função anônima convencional
}

() => {
    // Arrow Function
}

You can read more about it here

    
06.08.2016 / 02:49
3

I believe that in this case the ideal would be to use a variable to store the reference to this of the class

class Teste{
    metodoUm(){
        var _this = this;
        $('input').each(function () {
            // $(this) adicionado para referenciar o jQuery
            _this.metodoDois($(this)); 
        });
    }

    metodoDois(t){
        console.log(t);
    }
}
teste = new Teste();
teste.metodoUm();
    
06.08.2016 / 02:30
1

You could call class Teste() , and for this selection within the loop you could use $(this) :

class Teste {
  metodoUm() {
    $('input').each(function() {
      teste.metodoDois($(this));
    });
  }
  metodoDois(t) {
    console.log(t);
  }
}
teste = new Teste();
teste.metodoUm();
    
06.08.2016 / 02:16