JavaScript __proto__将影响对象中的原始函数

JavaScript __proto__ will affect the original function in the Object?

本文关键字:原始 函数 影响 proto JavaScript 对象      更新时间:2023-09-26
函数

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__已被弃用。而是将类的原型分配给您尝试从中继承的类的新实例,然后再向该类添加新的原型方法。

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 demo: https://jsfiddle.net/bkmLx30d/1/

您已经更改了此处对象的原型authors[0].__proto__ = new Person();,因此您在authors中的第一个Author对象现在有一个设置为Person()对象的原型。

当你做authors[0].getBooks()时,authors[0]会在原型中搜索getBooks(),但找不到它,因为Person.prototype没有getBooks(),因此给出错误。