[英]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.