JS原型对象没有继承? [英] JS prototype objects not inherited?

查看:121
本文介绍了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?

推荐答案


为什么孩子没有继承财产?

Why the child did not inherit property?

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

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



<你不应该创建一个Parent实例来设置Child的原型(改为使用Object.create),并在你的注释中将Child的原型设置为Parent.prototype,你不能这样做因为一个Child是一个父母,但父母不是孩子(例如:狗是动物,但动物不是狗,因为动物可能是蛇)。

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).

更多信息可以在此处找到构造函数和原型: https://stackoverflow.com/a/16063711/1641941

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆