簡體   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