Eug*_*ash 5 javascript prototypal-inheritance
可能重复:
Javascript构造函数属性的意义是什么?
在developer.mozilla.org 的Javascript 文档中,关于继承的主题有一个例子
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
Run Code Online (Sandbox Code Playgroud)
我想知道为什么我要在这里更新原型的构造函数属性?
每个函数都有一个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();
Run Code Online (Sandbox Code Playgroud)
所以最好确保它prototype.constructor()是正确的。