【发布时间】:2015-12-31 05:45:40
【问题描述】:
函数getBooks 已在Author.prototype 中定义。但不能在Author 对象中使用。当我使用__proto__ 继承Person 属性时。为什么Author 对象没有getBooks 功能?是__proto__的效果吗?
function Person(name){
this.name = name;
}
function Author(name,books){
Person.call(this,name);
this.books = books;
}
Person.prototype.getName = function(){
return this.name;
}
Author.prototype.getBooks = function() {
return this.books;
}
var john = new Person('John Smith');
var authors = new Array();
authors[0] = new Author('Dustin Diaz',['JavaScript Design Patterns']);
authors[1] = new Author('Ross Harmes',['JavaScript Design Patterns']);
authors[0].__proto__ = new Person();
console.log(john.getName());
console.log(authors[0].getName());
console.log(authors[0].getBooks())
【问题讨论】:
-
你不应该使用
__proto__,因为它是 FF 和 Chrome 中可用的供应商特定属性,并且不包含在原始规范中。 -
您能简单地解释一下您要完成的工作吗?为什么要尝试更改 Author 实例的原型,而不是将 Author 原型链接到 Person?
-
@Arkantos 好吧,她/他可以用
Object.setPrototypeOf替换__proto__,但这并不能改变他正在尝试做的基本问题。 -
谢谢大家对我的问题@torazaburo的帮助,我刚开始学习javascript面向对象编程。我尝试学习使用 proto 来继承一个对象。但是我不太了解proto的用法。另外,我不知道为什么仍然可以使用 Author 的变量。但是不能使用 Author Object 的功能。之后,使用 proto 继承 Person 属性。
标签: javascript prototype