gpt4 book ai didi

JavaScript __proto__ 会影响Object中原来的函数吗?

转载 作者:行者123 更新时间:2023-11-27 23:31:29 26 4
gpt4 key购买 nike

函数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__deprecated 。相反,在向该类添加新的原型(prototype)方法之前,请将类的原型(prototype)分配给您尝试继承的类的新实例。

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/

关于JavaScript __proto__ 会影响Object中原来的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com