How to create an object with two or more instances in JavaScript?

2

In JavaScript I know you can create an instance of a class using 'new'

new Classe

And how to create an object that is multi-class instance? For example

new Classe, OutraClasse...

I think this might be possible because it warns true :

var el = document.createElement('a');
alert(el instanceof HTMLElement && el instanceof HTMLAnchorElement);

In addition, el has more than 2 instances ...

    
asked by anonymous 28.08.2016 / 21:37

2 answers

3

Notice the following example:

class Animal {
    mostrarNome() {
        console.log('Eu sou um animal qualquer...');
    }
}

class Humano extends Animal {
    mostrarNome() {
        console.log('Eu sou um ser humano...');
    }
}

class Pessoa extends Humano {
    constructor(nome) {
        super();
        this.nome = nome;
    }
    mostrarNome() {
        console.log('Eu sou um ser humano... de nome ' + this.nome);
    }
}

var vaca = new Animal();
var sergio = new Pessoa('Sérgio');
vaca.mostrarNome(); // Eu sou um animal qualquer...
sergio.mostrarNome(); // Eu sou um ser humano... de nome Sérgio

console.log(vaca instanceof Animal, vaca instanceof Humano, vaca instanceof Pessoa); // true false false
console.log(sergio instanceof Animal, sergio instanceof Humano, sergio instanceof Pessoa); // true, true, true

What happens here is that you have classes that inherit from others. All classes that are descendants of others always give true when checking if they are an instance of the original. This is called inheritance and what happens is that the class from which it is inherited is written in the prototype of the new class. There are quite complete answers about this, as @bigown has indicated.

I created this example to realize that it is possible what you want. Simply by using extends in syntax ES2015, or by copying the prototype by hand with:

var NovaClasse = Object.create(ClasseAntiga);
    
28.08.2016 / 21:53
3

There is only one instance created. An instance can have more than one type, as long as there is a hierarchy between them. Then el is of type HTMLAnchorElement which in turn was inherited from HTMLElement , with this object satifaz at least these two types, after all everything that exists in the "class" base is available in the derived "class" / p>

Note that the normal JavaScript is to use prototypes and not classes. see more at Is there a JavaScript class? , Javascript is an Object Oriented Language? and What is Javascript Prototype? .

    
28.08.2016 / 21:46