gpt4 book ai didi

javascript - Javascript继承对象需要 "Subclass.prototype.constructor = Subclass"吗?

转载 作者:行者123 更新时间:2023-11-29 15:49:13 27 4
gpt4 key购买 nike

考虑以下示例,其中 Student 继承自 Person:

function Person(name) {
this.name = name;
}
Person.prototype.say = function() {
console.log("I'm " + this.name);
};

function Student(name, id) {
Person.call(this, name);
this.id = id;
}
Student.prototype = new Person();
// Student.prototype.constructor = Student; // Is this line really needed?
Student.prototype.say = function() {
console.log(this.name + "'s id is " + this.id);
};

console.log(Student.prototype.constructor); // => Person(name)

var s = new Student("Misha", 32);
s.say(); // => Misha's id is 32

如您所见,实例化一个 Student 对象并调用其方法工作得很好,但是 Student.prototype.constructor 返回 Person(name),这对我来说似乎是错误的。

如果我添加:

Student.prototype.constructor = Student;

然后 Student.prototype.constructor 按预期返回 Student(name, id)

我应该总是添加 Student.prototype.constructor = Student 吗?

需要的时候可以举个例子吗?

最佳答案

阅读这个 SO 问题 Prototype inheritance. obj->C->B->A, but obj.constructor is A. Why? .

它应该会给你一个答案。


关于javascript - Javascript继承对象需要 "Subclass.prototype.constructor = Subclass"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7762920/

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