简体   繁体   中英

JavaScript __proto__ will affect the original function in the Object?

The function getBooks has been defined in the Author.prototype . But it can't be used in the Author Object. When I am using the __proto__ to inherits the Person property. Why the does the Author Object have no getBooks function? Is it the effect of __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 . 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/

you've changed the prototype of the object here authors[0].__proto__ = new Person(); , so your first Author object in authors now has a prototype that's set to a Person() object .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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