JS原型对象没有继承

JS原型对象没有继承

本文介绍了JS原型对象没有继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我在玩JS原型继承时遇到的一个奇怪的输出。

My question is about a strange output that I came across while playing with JS prototypal inheritance.

请看一下:

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 the child did not inherit property?

当然如果我这样做:

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"}

预期输出:c和


[object Object] {
  variable: "c"
}

有没有人知道为什么对象'原型'没有被继承而'原型'的正常属性是?

does anyone know why the object 'prototype' is not beeing inherited while a normal property of 'prototype' is?

推荐答案

重新分配和变异之间的区别

difference between re assigning and mutating

重新分配:

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

变异:

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



You should not create an instance of Parent to set the prototype of Child (use Object.create instead) and in your comments you set the prototype of Child to be Parent.prototype, you can't do that because a Child is a Parent but a Parent isn't a Child (for example: a Dog is an Animal but an Animal is not a Dog because Animal could be a Snake).

更多信息可以在此处找到构造函数和原型:

More on constructor functions and prototype can be found here: https://stackoverflow.com/a/16063711/1641941

这篇关于JS原型对象没有继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:39