繁体   English   中英

JavaScript __proto__是否会影响对象中的原始功能?

[英]JavaScript __proto__ will affect the original function in the Object?

函数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演示: https ://jsfiddle.net/bkmLx30d/1/

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

当您执行authors[0].getBooks()authors[0]将在原型中搜索getBooks() ,但找不到它,因为Person.prototype没有getBooks()并给出了错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM