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