什么时候需要在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()
是正确的。
'var st2 = st.constructor();'错过了'new'关键字。它应该是'var st2 = new st.constructor();' – golem