为什么有必要设置原型构造函数? [英] Why is it necessary to set the prototype constructor?

查看:111
本文介绍了为什么有必要设置原型构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关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);

现在当我们创建一个新的学生并复制它?

Now what happens when we create a new Student and copy it?

var student1 = new Student("trinth");  
console.log(student1.copy() instanceof Student); // => false

副本不是学生的实例。这是因为(没有明确的检查),我们无法从base类返回 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆