js constructor的实际作用分析
2024-05-06 14:23:06
供稿:网友
代码如下:
<script> Function.prototype.createInstance = function(){
var T = function(){};
T.prototype = this.prototype;
T.constructor = this;
var o = new T();
this.apply(o, arguments);
return o;
}</script>
说下上面代码里面 T.constructor = this这句话,我感觉这句话没有什么实际作用,
本身T.constructor应该是为Funtion,为什么要给它设定为Funtion的实例呢,
代码如下:
<script>
Function.prototype.$extends = function(p){
this.$super = p;
var fn = function(){};
fn.prototype = p.prototype;
this.prototype = new fn();
//这句是我自己加的,保证构造出子类实例的constructor依然指向子类的构造器函数
this.prototype.constructor=this;
//-----------------------------
return this;
};
function Animal(){
}
function Cat(){
}
Cat.$extends(Animal);
var bb=new Cat();
alert(bb.constructor);
//但是(this.prototype.constructor=this)这种做法通过bb这个对象无法回朔到Animal的原型
//下面语句依然返回Cat这个函数,而不是Animal
alert(bb.constructor.prototype.constructor)
</script>
还有上面这句代码,我自己加了1句,修正了子类构造器依然指向子类函数,但是对象的原型链的回朔不能到达父类原型,解决办法是
去掉this.prototype.constructor=this;既不给原型设置constructor属性,而是给实例设置一个constructor属性,如下代码
代码如下:
<script>
Function.prototype.$extends = function(p){
this.$super = p;
var fn = function(){};
fn.prototype = p.prototype;
this.prototype = new fn();
return this;
};
function Animal(){
}
function Cat(){
this.constructor= arguments.callee;
}
Cat.$extends(Animal);
var bb=new Cat();
alert(bb.constructor);
//这种做法可以通过bb这个对象回朔到Animal的原型
alert(bb.constructor.prototype.constructor)
</script>
最后分析下constructor的实际作用
代码如下:
<script>
//定义函数
var f=function(){
}
//这里显示true,因为f的构造器是Funtion,f内部的原型属性_proto_被赋值为构造器的prototype也就是Function的prototype
//instanceof检查f内部的_proto_是否与Function.prototype有共同的结点,如果有则返回true
alert(f instanceof Function)
//obj是f的实例
var obj=new f;
//obj内部的原型属性_proto_在new f时被赋值为f.prototype,显然f.prototype与Function.prototype没有共同的结点,因此显示false
alert(obj instanceof Function)
//为了让obj成为Function的实例也就是(obj instanceof Function)显示true
//只需要f.prototype=Function.prototype
f.prototype=Function.prototype;
//但是我不推荐上面这种做法,因为对f.prototype的修改会破坏了Function.prototype,例如f.prototype.name="51js"会给Function的原型也加上1个name属性