什么时候需要在Javascript中设置类的'prototype.constructor'属性?

问题描述:

可能重复:
What it the significance of the Javascript constructor property?什么时候需要在Javascript中设置类的'prototype.constructor'属性?

在JavaScript docs在developer.mozilla.org,继承的话题有一个例子

// 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();constructor属性prototype正指向Person函数,所以你需要重置它。

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

constructor该属性是有用的,例如,在下列情况下(当你需要克隆的对象,但不知道究竟是什么功能创造了它):

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

所以最好以确保prototype.constructor()是正确的。

+0

'var st2 = st.constructor();'错过了'new'关键字。它应该是'var st2 = new st.constructor();' – golem