函数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__
是deprecated。而是在将新的原型方法添加到该类之前,将该类的原型分配给您要继承的该类的新实例。
function Author(name, books) {
Person.call(this, name);
this.books = books;
}
Author.prototype = new Person();
Author.prototype.constructor = Author;
Author.prototype.getBooks = function() {
return this.books;
};
JSFiddle演示:https://jsfiddle.net/bkmLx30d/1/