0

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__.

Tea
  • 873
  • 2
  • 7
  • 25

1 Answers1

0

When a function is created, its body it not evaluated, therefore the assignment to SlimZ2.prototype has no effect when you call new for the first time:

let SlimZ2 = function SlimZ2(name) {
    this.name = name;
    SlimZ2.prototype = {
        X: 'hey',
        constructor: SlimZ2
    }
};

let s2 = new SlimZ2("Lili")
console.log(s2.X)

let s3 = new SlimZ2("Lili")
console.log(s3.X)
gog
  • 10,367
  • 2
  • 24
  • 38
  • 1
    We can also observe that `s2.__proto__` is not equal to `s3.__proto__`. Looks like s2 was created with the old prototype (the default one without 'X' etc), but then the prototype was re-assigned (replaced with a different object) after the first call. – qrsngky Mar 18 '23 at 09:12