[英]Javascript Simple Prototypal Inheritance
I'm playing around in the console, trying to understand prototypal inheritance. 我在控制台里玩,试图了解原型继承。 I'm familiar with classical inheritance, but I've never used any inheritance in my JS work.
我熟悉经典继承,但我从未在JS工作中使用过任何继承。
If I have: 如果我有:
var foo = {
cat: "oliver"
}
var bar = Object.create(foo);
foo.prototype = {
dog: "rover"
}
When I do: 当我做:
dir(bar.dog)
or 要么
dir(foo.dog)
I expect to see rover
but they both come back as undefined
. 我希望看到
rover
但他们都回归undefined
。
What am I missing? 我错过了什么?
Thanks in advance. 提前致谢。
You are seeing this because of this line: 你看到这个是因为这一行:
foo.prototype = {
dog: "rover"
}
You can't change an object's prototype after you create that object. 创建该对象后,无法更改对象的原型。
What you can do is modify the existing prototype like this: 您可以做的是修改现有原型,如下所示:
foo.dog = "rover";
Remember that foo
is the prototype of bar
. 请记住,
foo
是bar
的原型。
The prototype members are only available when you instantiate it. 原型成员仅在您实例化时才可用。
foo.cat
is available because it's like "a static" property (from languages that have this kind of code support, like PHP for example). foo.cat
是可用的,因为它类似于“静态”属性(来自具有这种代码支持的语言,例如PHP)。 Also, you should inherit from the foo
prototype when doing your Object.create
此外,在执行
Object.create
时,您应该继承foo
原型
var foo = function(){ };
foo.cat = "oliver";
var bar = Object.create(foo.prototype);
foo.prototype.dog = "rover";
console.log(bar.dog); // yields "rover", modifying the prototype of "foo" alter the members of "bar" instance
this would be the correct code to accomplish what you are trying: 这将是完成您正在尝试的正确代码:
var foo = Object.create({dog:'rover'});
foo.cat = 'oliver';
var bar = Object.create(foo);
this way foo
inherits from an object with a property called dog
, then bar
inherits from that same object because it inherits from foo
这种方式
foo
继承自一个名为dog
的属性的对象,然后bar
继承自同一个对象,因为它继承自foo
Now, check with bar.dog
and bar.cat
it prints rover
and oliver
respectively 现在,请与
bar.dog
和bar.cat
它打印rover
和oliver
分别
notice that .prototype
only works to access or set the prototype object of functions, what you're doing in that code is wrong, this is correct: 请注意
.prototype
只能用于访问或设置函数的原型对象,你在该代码中所做的是错误的,这是正确的:
var a = function(){
}
a.prototype = {};
to access the prototype of an object you do it like this: 要访问对象的原型,你可以这样做:
a = {};
a.\__proto__.foo = 'bar';
however this allows you to get or set properties of that prototype object but not replace it for a different one. 但是,这允许您获取或设置该原型对象的属性,但不能将其替换为另一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.