在MDN文章“面向对象的Java语言简介”中有关继承的部分中,我注意到它们设置了prototype.constructor:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
这有任何重要目的吗?可以省略吗?
它并不总是必需的,但是它确实有其用途。假设我们想在基Person
类上创建一个copy方法。像这样:
// 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
并复制它时会发生什么?
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => false
该副本不是的实例Student
。这是因为(没有显式检查),我们无法Student
从“基”类返回副本。我们只能返回Person
。但是,如果我们重置了构造函数:
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
...然后一切都按预期进行:
var student1 = new Student("trinth");
console.log(student1.copy() instanceof Student); // => true
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句