Use of class.apply in the context of specialized class

3

I saw an example dealing with parent class and daughter class where, at the beginning of the specialized class, it looked like this:

var ClasseFilha = function ClasseFilha (){
    ClassePai.apply(this, arguments);

    ...
};

Although understand how apply works and see how the child class modifies itself in the second row (using this before and after apply brings different results), I get confused as ClassePai.apply( ) modify ClasseFilha without a direct assignment on a variable, for example.

I would like a more theoretical explanation for this, if possible.

    
asked by anonymous 14.06.2017 / 16:10

2 answers

3

Briefly, this apply will execute the constructor of the parent class in the context of the child class. That's what it does, it calls a function forcing a value to this within it. That is, any reference to this in constructor ClassePai will be referring to the this that has just been created in the execution of new ClasseFilha(...) .

You said:

  

I'm confused as ClassePai.apply() modify ClasseFilha without a direct assignment on a variable

Actually you are not modifying ClasseFilha (which is a constructor), but an object being instantiated with new ClasseFilha() . And not necessarily you're modifying, it depends on what the ClassePai constructor does. If you are familiar with OOP, the apply line is equivalent to a super() call in languages that implement OOP based on classes (# #).

14.06.2017 / 16:43
3

When you "lend" this via ClassePai.apply(this, arguments); you allow ClassePai to modify this that belongs to ClasseFilha . This allows you to extend the class if the code so desires.

An example:

function ClassePai(nome, idade) {
  this.nome = nome;
  this.idade = idade;
  this.dizerNome = function() {
    console.log(this.nome);
  }
}

var ClasseFilha = function ClasseFilha() {
  ClassePai.apply(this, arguments);
  this.naturalidade = arguments[2];
  this.naturalDe = function(){
    console.log(this.naturalidade);
  }
};

var pessoaA = new ClasseFilha('Pedro', 34, 'Portugal');
var pessoaB = new ClasseFilha('Ana', 34, 'Brazil');

pessoaA.dizerNome();
pessoaB.dizerNome();
pessoaB.naturalDe();

The explanation of @bfavaretto is quite complete.

    
14.06.2017 / 16:49