Javascript原型对象不能继承吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Javascript原型对象不能继承吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1589字,纯文字阅读大概需要3分钟。
内容图文
![Javascript原型对象不能继承吗?](/upload/InfoBanner/zyjiaocheng/679/a9c33d9e4cd7458387f000d7ce2be21b.jpg)
我的问题是我在玩JS原型继承时遇到的奇怪输出.
请看一下:
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'}
为什么孩子没有继承财产?
当然,如果我这样做的话:
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" }
有谁知道为什么对象“原型”不被继承而普通属性为“原型”呢?
解决方法:
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的原型(改用Object.create),并且在注释中将Child的原型设置为Parent.prototype,不能这样做,因为Child是Parent,但是父母不是孩子(例如:狗是动物,但动物不是狗,因为动物可能是蛇).
有关构造函数和原型的更多信息,请参见:https://stackoverflow.com/a/16063711/1641941
内容总结
以上是互联网集市为您收集整理的Javascript原型对象不能继承吗?全部内容,希望文章能够帮你解决Javascript原型对象不能继承吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。