为什么需要设置原型构造函数? [英] Why is it necessary to set the prototype constructor?
问题描述
在 MDN 文章中关于继承的部分面向对象的Javascript简介,我注意到他们设置了prototype.constructor:
In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
这有什么重要目的吗?可以省略吗?
Does this serve any important purpose? Is it okay to omit it?
推荐答案
它并不总是必要的,但它确实有它的用途.假设我们想在基本的 Person
类上创建一个复制方法.像这样:
It's not always necessary, but it does have its uses. Suppose we wanted to make a copy method on the base Person
class. Like this:
// define the Person Class
function Person(name) {
this.name = name;
}
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};
// define the Student class
function Student(name) {
Person.call(this, name);
}
// inherit Person
Student.prototype = Object.create(Person.prototype);
现在当我们创建一个新的 Student
并复制它时会发生什么?
Now what happens when we create a new Student
and copy it?
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => false
该副本不是Student
的实例.这是因为(没有显式检查),我们无法从基本"类返回 Student
副本.我们只能返回一个Person
.但是,如果我们重置了构造函数:
The copy is not an instance of Student
. This is because (without explicit checks), we'd have no way to return a Student
copy from the "base" class. We can only return a Person
. However, if we had reset the constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
...然后一切都按预期进行:
...then everything works as expected:
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => true
这篇关于为什么需要设置原型构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!