理解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/ 叙述了所有实现继承的方式

转载于:https://www.cnblogs.com/sking7/archive/2011/10/09/2203702.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值