您的位置:首页 > 其它

理解call,this指针(用call实现继承),prototype模式实现继承的易错点

2011-10-09 14:57 344 查看
今天看别人写的博客看到有人说js实现继承刻用call实现,自己寡闻就看了下
function SuperType(name){
    this.name=name;
    this.colors=["red","blue","green"];
  }
  function SubType(){
    SuperType.call(this);  //继承了SuperType

  }
一直不解。。知道自己写了个测试函数。。
<script>
function superType(name){
this.color="re";
this.name=name;
}
var age=10;
function subType(){
superType.call(this,"name");
//supertype函数的this为subType中的this,也就是说,subType中this指针称为superType的内部指针。。。
alert(this.age);//10
alert(this.color);//re
}
subType();
//var sub=new subType();
//alert(sub.color);
//alert(sub.name);
//alert(this.color);
alert(this.age);//打印出10
alert(this.color);//re
</script>

摘自:http://ued.alimama.com/front-end/javascript-extend/ 叙述了所有实现继承的方式
这种方式和subType(),这种方式是不一样的,,this指针指向的不同
上面的形式,this指针其实指向的是window对象。。
用注释的语句运行呢。。
<script>
function superType(name){
this.color="re";
this.name=name;
}
var age=10;
function subType(){
superType.call(this,"name");//supertype函数的this为subType中的this,也就是说,subType中this指针称为superType的内部指针。。。
alert(this.age);//undefinde
alert(this.color);//re
}
//subType();
var sub=new subType();
//alert(sub.color);
//alert(sub.name);
//alert(this.color);
alert(this.age);//10
alert(this.color);//undefined
</script>
这时this就不再是全局的this指针了。。而是sub这个对象、、、
----------------------------------------------------------
下面讲一下  prototype的继承方式。。
如果”WD”的prototype对象,指向一个MED的实例,那么所有”WD”的实例,就能继承MED了。
如下实现
function MED(){
this.aim = "营销体验设计";
}
function WD(){
this.skill = "java";
}
WD.prototype=new MED();
WD.prototype.constructor = WD;
//任何一个prototype对象都有一个constructor属性,指向它的构造函数。也就是
//说,WD.prototype 这个对象的constructor属性,是指向WD的。
//----------------------------
//这样就实现了继承
//-------------华丽的分割线-----------
///有人想直接赋值

WD.prototype = MED.prototype;
WD.prototype.constructor = WD;
//这样有什么问题呢??
//这样做的优点是效率比较高(不用执行和建立MED的实例了),
//比较省内存。缺点是 WD.prototype和MED.prototype现在指向了同一个对象,
//那么任何对WD.prototype的修改,都会反映到MED.prototype。

摘自:http://ued.alimama.com/front-end/javascript-extend/ 叙述了所有实现继承的方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: