是“Subclass.prototype.constructor = Subclass”吗?在Javascript中继承对象时需要吗?

发布于 2024-12-09 12:40:20 字数 1078 浏览 0 评论 0原文

考虑以下示例,其中 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 对象并调用其方法工作得很好,但是 < code>Student.prototype.constructor 返回 Person(name),这对我来说似乎是错误的。

如果我添加:

Student.prototype.constructor = Student;

那么 Student.prototype.constructor 按预期返回 Student(name, id)

我应该始终添加 Student.prototype.constructor = Student 吗?

需要时您能举个例子吗?

Consider the following example where Student inherits from 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

As you can see, instantiating a Student object and calling its methods works just fine, but Student.prototype.constructor returns Person(name), which seems wrong to me.

If I add:

Student.prototype.constructor = Student;

then Student.prototype.constructor returns Student(name, id), as expected.

Should I always add Student.prototype.constructor = Student?

Could you give an example when it is required ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可爱咩 2024-12-16 12:40:20

阅读这个SO问题 原型继承。 obj->C->B->A,但是 obj.constructor 是 A。为什么?

它应该会给你一个答案。


Read this SO question Prototype inheritance. obj->C->B->A, but obj.constructor is A. Why?.

It should give your an answer.


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文