函数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/

09-25 18:47
查看更多