是“Subclass.prototype.constructor = Subclass”吗?在Javascript中继承对象时需要吗?
考虑以下示例,其中 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
阅读这个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.