最高半折刷qq各种业务和钻(家里人自己开的,尽管放心,大家多捧捧场)

sking7

导航

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

今天看别人写的博客看到有人说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对象。。
用注释的语句运行呢。。
 1 <script>
2 function superType(name){
3 this.color="re";
4 this.name=name;
5 }
6 var age=10;
7 function subType(){
8 superType.call(this,"name");//supertype函数的this为subType中的this,也就是说,subType中this指针称为superType的内部指针。。。
9 alert(this.age);//undefinde
10 alert(this.color);//re
11 }
12 //subType();
13 var sub=new subType();
14 //alert(sub.color);
15 //alert(sub.name);
16 //alert(this.color);
17 alert(this.age);//10
18 alert(this.color);//undefined
19 </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/ 叙述了所有实现继承的方式

posted on 2011-10-09 14:57  G.N&K  阅读(397)  评论(0编辑  收藏  举报