原型继承-什么时候需要设置'prototype.constructor'属性

prototypal inheritance - When is it necessary to set the 'prototype.constructor' property of a class in Javascript?

本文关键字:constructor 属性 prototype 设置 继承 什么时候 原型      更新时间:2023-09-26

可能重复:
Javascript构造函数属性的意义是什么?

在developer.mozilla.org上的Javascript文档中,关于继承的主题,有一个示例

// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

我想知道为什么要在这里更新原型的构造函数属性?

每个函数都有一个prototype属性(即使您没有定义它(,prototype对象只有一个属性constructor(指向函数本身(。因此,在你做了Student.prototype = new Person();之后,prototypeconstructor属性指向Person函数,所以你需要重置它。

你不应该认为prototype.constructor是神奇的东西,它只是一个指向函数的指针。即使您跳过第Student.prototype.constructor = Student;行,第new Student();行也会正常工作。

constructor属性很有用,例如在以下情况下(当您需要克隆对象,但不知道是什么函数创建了它(:

var st = new Student();
...
var st2 = st.constructor();

因此最好确保CCD_ 12是正确的。