关于Javascript中的constructor的一些理解
最近在看Javascript的继承机制时,发现每个对象都会有一个constructor函数,刚开始不怎么明白,经过一番查找,对其有了一定的了解。其实constructor始终指向创建当前对象实例的(构造)函数。我们都知道,任何函数都是Function类的一个实例,那么根据上述可知:任何函数的constructor属性都指向Function类,而Function类的constructor又指向谁呢?其实也是Function类本身,也就构成了一个递归。至于这个constructor函数有什么用呢?根据我的理解有以下几个用法:
1. 追踪对象的原始构造函数。
var cat1=new Cat();
var cat2=new cat1.constructor();//这里cat1.constructor()的就是Cat
再例如
我定义一个函数
function clone(obj)
{
//这里不知道o的类型
var newobj=new obj.constructor();//就可以得到obj的对象类型,
}
2.在 JavaScript 中,每个函数都有名为“prototype”的属性,用于引用原型对象。此原型对象又有名为“constructor”的属性,它反过来引用函数本身。这是一种循环引用,如图:
function extend(Child,Parent)//继承封装
{
var F=function (){}
F.prototype=Parent.prototype;
Child.prototype=new F();
//Child.prototype.constructor=Child;
}
function Animals()
{
}
Animals.prototype.species="猫科";
function Cat(name,age)
{
this.age=age;
this.name=name;
}
extend(Cat,Animals);
var cat1=new Cat("heshan","22");
//这时就会出现一个有趣的问题
cat1.constructor ===Cat //false
Cat.prototype.constuctor==Cat //false
这是为什么呢?
问题在红色部分,因为将一个新的对象赋给了继承对象,将会覆盖了本身的constructor函数,因此导致了原型链的
破坏。