One could say that the prototype is the "predecessor of classes" for Javascript object orientation. However, it is worth emphasizing that the classes that were implemented in Ecmascript 2015 are only one syntactic sugar to the prototype, and are not a new object orientation model. Underneath the scenes, everything is still the prototype. :)
Thus, when you create a function in Javascript, it can end up being used as a "class", including methods and properties - static or instance; the latter can be defined through the prototype
.
function Person(name) {
// Corresponde ao construtor de uma classe.
console.log('Objeto construído.');
this.name = name;
}
// Definimos uma propriedade da instância.
Person.prototype.isHuman = true;
// Definimos uma propriedade da instância através do prototype.
Person.prototype.greet = function() {
console.log(`Hello! My name is ${this.name}.`);
};
// E um método estático:
Person.a = function() {
console.log('Método estático.');
};
Person.a();
const p = new Person('Luiz');
console.log(p.name);
p.greet();
p.a(); // Erro, já que `a` é um método estático.
Personally, I see no reason to use the prototype, since it is much more verbose than a class. See a code using classes that does exactly the same thing as the previous one:
class Person {
constructor(name) {
console.log('Objeto construído.');
this.name = name;
}
isHuman = true;
greet() {
console.log(`Hello! My name is ${this.name}.`);
}
static a() {
console.log('Método estático.');
}
}
Person.a();
const p = new Person('Luiz');
console.log(p.name);
p.greet();
p.a(); // Erro, já que `a` é um método estático.
So, go by which preference you want to use.
And in:
How can I create a property in a method in Javascript?
In the case of query selector, className
or firstChild
are not properties of the method querySelector
in itself. They are, in fact, properties of the object that is returned by such methods. It is the same thing as doing this:
const fakeDocument = {
querySelector: () => {
// Note que estamos retornando um objeto do nosso método.
return {
firstChild: 'Foo',
className: 'Bar'
};
}
};
console.log(fakeDocument.querySelector().firstChild); // Foo
console.log(fakeDocument.querySelector().className); // Bar
And it’s not even necessary to use prototype
or classes to achieve that result. :)
Show, thank you so much for the attention @Luiz, I understood clearly now, your reply was very helpful, thank you!
– Magno