constructor属性:
链接:http://developer.51cto.com/art/200907/134913.htm
默认情况下,prototype 属性都会自动获得一个 constructor 属性。
实例对象的constructor属性始终指向创建当前对象的构造函数。
实例对象的prototype的constructor属性默认指向对象的构造函数。
当重新定义了实例对象的prototype属性时(覆盖了),要重新指定prototype的constructor属性。
我们来看一个例子:
var arr = [1, 56, 34, 12]; // 等价于 var foo = new Array(1, 56, 34, 12); console.log(arr.constructor === Array); // true var Foo = function() { }; // 等价于 var foo = new Function(); console.log(Foo.constructor === Function); // true var obj = new Foo(); // 由构造函数实例化一个obj对象 console.log(obj.constructor === Foo); // true // 将上面两段代码合起来,就得到下面的结论 console.log(obj.constructor.constructor === Function); // true function Person(name) { this.name = name; }; Person.prototype.getName = function() { return this.name; }; var p = new Person("ZhangSan"); console.log(p.constructor === Person); // true console.log(Person.prototype.constructor === Person); // true // 将上两行代码合并就得到如下结果 console.log(p.constructor.prototype.constructor === Person); // true
再看一个例子:
function Person(name) { this.name = name; }; Person.prototype = { //我们重新定义对象的prototype getName: function() { return this.name; } }; var p = new Person("ZhangSan"); console.dir(p.constructor); //function console.log(p.constructor === Person); // false console.log(Person.prototype.constructor === Person); // false console.log(p.constructor.prototype.constructor === Person); // false console.log(p.constructor === Object); // true console.log(Person.prototype.constructor === Object); // true console.log(p.constructor.prototype.constructor === Object); // true
为什么呢?因为:
//因为覆盖Person.prototype时,等价于进行如下代码操作: Person.prototype = new Object({ getName: function() { return this.name; } }); //而constructor属性始终指向创建自身的构造函数,所以此时其实是: Person.prototype.constructor === Object
怎么修正这种问题呢?:
//方法也很简单,重新覆盖Person.prototype.constructor即可: function Person(name) { this.name = name; }; Person.prototype = { //我们重新定义对象的prototype getName: function() { return this.name; } }; Person.prototype.constructor = Person; //重新制定constructor的指向 var p = new Person("ZhangSan"); console.log(p.constructor === Person); // true console.log(Person.prototype.constructor === Person); // true console.log(p.constructor.prototype.constructor === Person); // true