简体   繁体   English

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

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

The function getBooks has been defined in the Author.prototype . 函数getBooks已在Author.prototype定义。 But it can't be used in the Author Object. 但是不能在Author对象中使用。 When I am using the __proto__ to inherits the Person property. 当我使用__proto__继承Person属性时。 Why the does the Author Object have no getBooks function? 为什么Author对象没有getBooks函数? Is it the effect of __proto__ ? __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__ is deprecated . __proto__过时 Instead assign the prototype of the class to a new instance of the class you're trying to inherit from before adding new prototype methods to that class. 而是在将新的原型方法添加到该类之前,将该类的原型分配给您要继承的该类的新实例。

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

you've changed the prototype of the object here authors[0].__proto__ = new Person(); 您已经在这里更改了对象的原型authors[0].__proto__ = new Person(); , so your first Author object in authors now has a prototype that's set to a Person() object . ,因此您在authors第一个Author对象现在具有一个设置为Person()对象的原型。

when you do authors[0].getBooks() , authors[0] will search for getBooks() in the prototype but won't find it since Person.prototype doesn't have a getBooks() and thus give an error. 当您执行authors[0].getBooks()authors[0]将在原型中搜索getBooks() ,但找不到它,因为Person.prototype没有getBooks()并给出了错误。

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

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