I am such a person who needs to know everything in the depths ... So, I went through many taught subjects, and I put my foot in the depths of the prototype heritage.
I have a clear idea of how this works in ES5 (each function has this special prototype property that points to the object on which it is based. This object has a .constructor property that points to a function, etc.) .
So now let's look at an ES5 example:
function Bunny(name) {
this.name = name
}
Bunny.prototype.sayName = function() {
console.log('Im',this.name)
}
This is pretty clear: the Bunny function receives an argument namethat will be assigned to the new object.
The next line adds a function to the function prototype, which will return the current name.
Now let's see the ES6 class:
class Fox{
constructor(name){
this.name = name;
}
sayName() {
console.log('Im', this.name)
}
}
: Constructor Bunny. sayName , sayName Bunny.
:
let bunny = new Bunny('Henry');
let fox = new Fox('Jerry');
, :
console.log(Object.getPrototypeOf(bunny))
console.log(Object.getPrototypeOf(fox))
?
{ sayName: [Function] }
{}
?
, , sayName Bunny. :
function Bunny(name) {
this.name = name
this.sayName = function() {
console.log('Im',this.name)
}
}
:
{}
{}
, :
console.log(bunny.hasOwnProperty('sayName'))
console.log(fox.hasOwnProperty('sayName'))
, fox sayName , , . - ? ?