Why is the replacement of the prototype objects of the constructor function not reflected in the objects?

If I just use obj.prototype.property = val, everything will be fine, code like

function animal() {}
var frog = new animal();
animal.prototype.color = 'Green';
console.log(frog.color);
// 'Green'

But if I use obj.prototype = {key:val}after the new keyword, it will give me a undefinedcode like

function animal() {}
var frog = new animal();
animal.prototype = {
    color: 'Green'
};
console.log(frog.color);
// 'undefined' -- why?

And if I change the order that allows the prototype before the new keyword, it will be fine, so weird and why? because we know that prototype objects allow us to add properties to all instances of this object (even existing instances), right?

code for example

function animal() {}
animal.prototype = {
    color: 'Green'
};
var frog = new animal();
console.log(frog.color);
// 'Green'
+4
source share
2 answers

new [[Property]] .

function animal() {}
var frog = new animal();

console.log(Object.getPrototypeOf(frog) === animal.prototype);
# true

animal.prototype = {
    color: 'Green'
};

console.log(Object.getPrototypeOf(frog) === animal.prototype);
# false

console.log(frog.color);

console.log true, new animal prototype frog [[Prototype]] . , - animal prototype, frog [[Prototype]] , color. undefined.

, new, animal prototype ( ) frog. color.

, . ,

animal.prototype.color = 'Green';

animal.prototype - , ( , ) animal.prototype. , frog internal [[Prototype]] , animal.prototype.

+1

. prototype [[Prototype]] . new . , prototype, new, , . prototype, , :

function Animal(){}
var frog = new Animal();
Animal.prototype.color = 'green';
console.log(frog.color); // green
0

All Articles