javascript - JS原型(prototype)对象不继承?

标签 javascript prototype prototypal-inheritance

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

请看:

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

为什么 child 没有继承属性(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"
}

有谁知道为什么对象“prototype”没有被继承而“prototype”的一个普通属性是?

最佳答案

Why the child did not inherit property?

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

重新分配:

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

您不应该创建 Parent 的实例来设置 Child 的原型(prototype)(改为使用 Object.create),并且在您的评论中您将 Child 的原型(prototype)设置为 Parent.prototype,您不能这样做,因为 Child 是父对象但父对象不是子对象(例如:狗是动物,但动物不是狗,因为动物可能是蛇)。

更多关于构造函数和原型(prototype)的信息可以在这里找到:https://stackoverflow.com/a/16063711/1641941

关于javascript - JS原型(prototype)对象不继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23970431/

相关文章:

javascript - 为什么我不能得到默认值的参数长度?

使用带有原型(prototype)的 setInterval 的 JavaScript 上下文问题

javascript oop 访问从基础扩展 'class' 成员

javascript - 如果我们在 JavaScript 中填充 fn.bind(),为什么你必须检查 "this"的类型?

javascript - 为什么添加到原型(prototype)的方法没有给出 "not defined"的错误?

javascript - Windows 8 应用程序中的背景音频

javascript - 如何在kineticJS中绘制对象的动画路径?

javascript - OnClick 事件未触发

javascript - 为什么我的原型(prototype)函数中出现 'this.setData is not a function'?

javascript - 如果属性尚未由实例本身设置,为什么在更新原型(prototype)时更新实例的属性?