I'm learning F.prototype throw this site. After playing around for awhile, I'm getting confused when trying to understand prototype
. First, let me show my example:
let animal = {
jump: function () {
alert(`Hey ${this.name}, Bounce! Bounce! Bounce!`);
}
}
let SlimZ1 = function (name) {
this.name = name;
};
// I tried to import function from animal to SlimZ1 by this
SlimZ1.prototype = {
...animal,
constructor: SlimZ1
}
// And every time when I created an instance, it works fine.
let s1 = new SlimZ1("Lili")
s1.jump() // work
s1.__proto__ === SlimZ1.prototype // true because it equals {jump: ƒ, constructor: ƒ}
Now I tried to put prototype
inside function like this
let animal = {
jump: function () {
alert(`Hey ${this.name}, Bounce! Bounce! Bounce!`);
}
}
let SlimZ2 = function SlimZ2(name) {
this.name = name;
SlimZ2.prototype = {
...animal,
constructor: SlimZ2
}
};
// And every time when I created an instance, it works fine.
let s2 = new SlimZ2("Lili")
s2.jump() // STOP WORKING
s2.__proto__ === SlimZ2.prototype // false
// s2.__proto__ | {constructor: ƒ}
// SlimZ2.prototype | {jump: ƒ, constructor: ƒ}
The tutorial said F.prototype will be copied when new F() is called. But in the second case of my example, it doesn't. Can anyone help me to explain this problem?
P/s: I knew we can use different ways to bring prototype
inside F() constructor by using Object.assign
or this.__proto__
.