【发布时间】:2014-10-21 12:26:14
【问题描述】:
我正在尝试理解 Javascript 中的原型继承。对此已经提出了几个问题,但它们似乎并没有解决我的困惑。
How does JavaScript .prototype work?
What is the 'new' keyword in JavaScript?
互联网上也有一些很棒的资源。
http://www.webdeveasy.com/javascript-prototype/
http://javascriptissexy.com/javascript-objects-in-detail/
当我阅读这些资源时,我认为我理解了原型继承,但是当我在浏览器控制台中尝试一些测试时,我意识到我遗漏了一些东西。
基于以下代码示例:
(1) 为什么添加的原型函数description()在父对象animal上不可见?
(2) 为什么添加了description()函数后创建的对象现在缺少原来的对象属性:name和color? p>
例子:
创建一个简单的对象。
function animal(){
var name;
var colour;
}
根据原型动物
创建两个新对象> cat = new animal();
< animal {}
> cat.name = 'cat';
> cat.color = 'black';
> cat
< animal {name: "cat", color: "black"}
只为一个对象添加属性
> dog = new animal();
> dog.name = 'dog';
> dog.color = 'brown';
> dog.bite = 'hurts';
> dog
< animal {name: "dog", color: "brown", bite: "hurts"}
> animal.prototype.description = function(){
console.log('A ' + this.name + ' is ' + this.color); }
< function (){
console.log('A ' + this.name + ' is ' + this.color); }
添加一个新函数作为原型。这一切都按我的预期工作。
> animal
< function animal(){
var name;
var colour;
}
> dog
< animal {name: "dog", color: "brown", bite: "hurts", description: function}
> cat
< animal {name: "cat", color: "black", description: function}
这就是混乱。新功能 description 出现在现有的 dog 和 cat 对象上,但不会出现在父对象 animal
> cat.description;
< function (){
console.log('A ' + this.name + ' is ' + this.color); }
> cat.description();
< A cat is black
从父 animal 创建的新对象 cow 现在只有 description 功能,但没有 name > 或 颜色
> cow = new animal();
< animal {description: function}
> cow
< animal {description: function}
编辑
根据@Quince 的回答,我又回到了浏览器,但还是一头雾水:
>animal = function(){
this.name;
}
<function (){
this.name;
}
>animal
<function (){
this.name;
}
>cat = new animal();
<animal {}
>cat
<animal {}
在这种情况下,新对象 cat 似乎没有从父对象继承 name 属性。
【问题讨论】:
-
啊,如果您将它们设置为未定义或初始值,您会看到它们
function Animal(name, colour){ this.name = name; this.colour = colour; }
标签: javascript prototype