constructor属性始终指向创建当前对象的构造函数

一般情况下的constructor的属性非常容易理解。

var arr=[1,2,3,4,5];//等价于var arr=new Array(1,2,3,4,5);
alert(arr.constructor===Array)//true
var Foo=function(){}//等价于var Foo=new Function(){};
alert(Foo.constructor===Function);//true
//
由构造函数实例化一个obj对象
var obj=new Foo();
alert(obj.constructor===Foo);true

alert(obj.constructor.constructor===Function);true

但constructor遇到prototype时,有几点需要理清。

1.每个函数(F)都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数(F)。

function Person(name){
this.name=name;
}
Person.prototype.getName=function(){return this.name;}
var me=new Person('asan');
alert(me.constructor===Person);//true
alert(Person.prototype.constructor===Person)//true

2.当我们重定义构造函数的prototype属性时,注意constructor属性此时的指向

function Person(name){
this.name=name;
}
Person.prototype={
getName:function(){
return this.name;
}
}
var me=new Person('asan');
alert(me.constructor===Person);//false
alert(Person.prototype.constructor===Person)//false

为什么呢,原因是重定义Person.prototype时,等价于如下代码

Person.prototype=new Object({
getName:function(){
return this.name;
}
});

而constructor属性始终指向创建自身的构造函数,所以此时的Person.prototype.constructor属性指向Object

Person.prototype.constructor===Object;//true

怎么修正这个问题呢,很简单,重新把Person.prototype.constructor指向构造函数本身即可。

function Person(name){
this.name=name;
}
Person.prototype={
getName:function(){
return this.name;
}
}
Person.prototype.constructor=Person;
var me=new Person('asan');
alert(me.constructor===Person);//true
alert(Person.prototype.constructor===Person)//true







posted on 2012-03-02 15:19  杭城小威  阅读(304)  评论(0编辑  收藏  举报