我的问题是关于我在玩 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/