gpt4 book ai didi

javascript - 直接分配.prototype进行类继承

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:25 27 4
gpt4 key购买 nike

我们知道执行继承的经典方法是 Teacher.prototype = Object.create(Person.prototype);,其中 Teacher 扩展 Person。但是,如果我直接赋值,它似乎也有效。

Teacher.prototype = Person.prototype;

我可以这样做吗?现在,Teacher 也可以访问所有 Person 的原型(prototype)方法。

最佳答案

你可以,但这意味着当你分配给 Teacher.prototype 的属性时,你将改变 Person.prototype,这可能是不可取的。

// Works:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
function Teacher(name) {
Person.call(this, name);
}
Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.teaches = function() {
return true;
}

const p = new Person('bob');
console.log(p.teaches()); // p.teaches is not a function, as expected and desired

比较

// Bad:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
function Teacher(name) {
Person.call(this, name);
}
Teacher.prototype = Person.prototype;
Teacher.prototype.teaches = function() {
return true;
}

const p = new Person('bob');
console.log(p.teaches()); // `true`... oops, but bob is not a Teacher, bob is just a Person

最好使用 Object.create 方法,以便 Teacher.prototype(至少在最初)是一个可以自由修改的空对象,它具有指向 Person.prototype内部原型(prototype)

请记住,对于真实代码(而不是为了弄清楚语言机制而用于思想实验的代码),您可以通过使用classextends关键字来避免大部分麻烦和语法噪音:

class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Teacher extends Person {
teaches() {
return true;
}
}
const p = new Person('bob');
console.log(p.teaches()); // p.teaches is not a function, as expected and desired

关于javascript - 直接分配.prototype进行类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58760756/

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