学习js原型与继承的时候,经常会碰到constructor,现在来揭开神秘面纱描述:所有对象都会从它的原型上继承一个 constructor 属性var o = new Object;o.constructor === Object; // truevar a = [];a.constructor === Array; // truevar a = new Array;a.constructor === Array // truevar n = new Number(3);n.constructor === Number; // true继承中的constructorfunction Person (name, age) { this.name = name, this.age = age}Person.prototype.setAge = function () { console.log(“111”)}function Student (name, age, price) { Person.call(this, name, age) this.price = price this.setScore = function () { }}Student.prototype = Object.create(Person.prototype)//用于设置原型Student.prototype.constructor = Student//重新分配原始构造函数var s1 = new Student(‘Tom’, 20, 15000)console.log(s1 instanceof Student, s1 instanceof Person) // true trues1.setAge() // 111console.log(s1) console.log(s1.constructor) //Student现在不手动重置构造函数function Person (name, age) { this.name = name, this.age = age}Person.prototype.setAge = function () { console.log(“111”)}function Student (name, age, price) { Person.call(this, name, age) this.price = price this.setScore = function () { }}Student.prototype = Object.create(Person.prototype)//用于设置原型// Student.prototype.constructor = Student//重新分配原始构造函数var s1 = new Student(‘Tom’, 20, 15000)console.log(s1 instanceof Student, s1 instanceof Person) // true trues1.setAge() // 111console.log(s1) console.log(s1.constructor) // Person可以看到除了s1的constructor不同,重置不重置原始构造函数对我们的继承没有影响。结论就是:constructor是用于识别对象是由哪个构造函数初始化的,对继承没影响可以看这篇文章:JS constructor探讨(一):为什么要设置prototype.constructor?But!! 什么情况下要手动重置构造函数??? 那就是你要调用constructor()的时候!!!此时constructor的指向就会产生影响来一个MDN上的列子:function Parent() {};function CreatedConstructor() {}CreatedConstructor.prototype = Object.create(Parent.prototype);CreatedConstructor.prototype.create = function create() { return new this.constructor();}new CreatedConstructor().create().create(); 为什么报错,因为CreatedConstructor.prototype.constructor为Parent,所以new CreatedConstructor().create()的结果是Parent{}这个对象,这个对象没有create方法,所以报错了解决办法:function Parent() {}; function CreatedConstructor() {} CreatedConstructor.prototype = Object.create(Parent.prototype); CreatedConstructor.prototype.constructor = CreatedConstructor; // set right constructor for further usingCreatedConstructor.prototype.create = function create() { return new this.constructor();} new CreatedConstructor().create().create(); // it’s pretty fine这时候需要重置CreatedConstructor的构造函数,使constructor重新指向自己参考文章:JS constructor探讨(一):为什么要设置prototype.constructor?Object.prototype.constructor