JS object objects not inherited?

My question is about the strange exit that I came across while playing with prototype JS inheritance.

Please take a look:

function Parent(){
}

Parent.prototype = {
  variable : 'a'
}; 


function Child(){
}

Child.prototype = new Parent();


child = new Child();

Parent.prototype =
{
  variable : 'c'
};


console.log(child.variable);  // output a
console.log(child.__proto__);  // [object Object] { variable: 'a'}

Why didn't the child inherit the property?

Of course, if I did it like this:

function Parent(){
}

Parent.prototype.variable = 'a'; 


function Child(){
}

Child.prototype = new Parent();


child = new Child();

Parent.prototype.variable = 'c';

console.log(child.variable); //  "c"
console.log(child.__proto__); //  [object Object] { variable: "c"}

Expected to exit: "c" and

[object Object] {
  variable: "c"
}

Does anyone know why the object 'prototype' is not inherited, but the normal property is 'prototype'?

+3
source share
3 answers

Why didn't the child inherit the property?

difference between reappointment and mutation

re assignment:

var org = {val:22};
var copy = org;
//re assigning org de references copy
//  before this line copy === org
//  but after this line it isn't
org = {val:44};
//what do you think the value of copy is
console.log(copy.val);//=22 re assigning org de references copy

Mutating:

var org = {val:22};
var copy = org;
org.val=33;//mutating org
//mutating copy (copy.val=11) would affect org
//  because org and copy are still the same (copy === org)
console.log(copy.val);//=33 because mutated org

Child ( Object.create), Child to be Parent.prototype, , Child , (: - , - , ).

: fooobar.com/questions/2287/...

+2

Child.prototype = new Parent(); Parent - Parent.prototype Child.prototype.__proto__.

: Parent.prototype.variable = 'c'; variable, , Child.prototype.__proto__, Child.

Parent.prototype = { variable: 'c' }; Parent.prototype . (Child.prototype.__proto__ - , .

+1

- , 'prototype' ...

[[Prototype]], , . [[Prototype]] , , .

, , [[Prototype]] Child.prototype, ., , .

When you later assign a new Parent.prototype that does not modify the [[Prototype]]instances that have already been created, therefore Child.prototype is still inherited from the original Parent.prototype, and therefore the child too.

... while the normal 'prototype' property is equal?

Because this simply adds a new property to an existing object, it does not assign the new object to the constructor prototype property.

+1
source

All Articles