C.T. Cheung
C.T. Cheung

Reputation: 19

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())

Upvotes: 1

Views: 61

Answers (2)

Miguel
Miguel

Reputation: 20633

__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/

Upvotes: 1

Ramanlfc
Ramanlfc

Reputation: 8354

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.

Upvotes: 0

Related Questions