js进阶02、构造函数的继承者们

上一篇找对象,找完对象得生孩子不是,生完孩子就得考虑继承问题,所以这篇的主题来了,叫做“如何将我的优良基因,继承给我女朋友们的孩子”。简直天才有木有?

书归正传,回到女票的生产那个构造函数。

 function girlFriend(){
     
this.mother="柳什么岩";
 }

然后她有了个儿子:
 function son(name,use){
     
this.name = name;
     
this.use = use;
 }

然后这个儿子怎么继承我的优良基因呢?有两种方法,第一个为使用call或apply方法:
 function son(name,use){
     
girlFriend.call(this);
     
this.name = name;
     
this.use = use;
 }

然后我们就可以new了,例如第一个儿子叫张岩,用途为坑爹;
 var son1=new son("张岩","坑爹");
我们可以在这个子对象里面找到他继承下来的书性:
 alert(son1.mother);//柳什么岩

第二种是利用prototype做继承,prototype是什么大家可以翻看一下上一篇
 son.prototype=new girlFriend();
首先我们将子对象的原型指向继承的那个对象girlFriend()。然后再new,就可以得到我们想要的效果啦!
 var son1=new son("张岩","坑爹");
 
alert(son1.mother);//柳什么岩

但是现在有一个问题,就是这个实例son1到底指向的是谁
首先我们看看son这对对象原型的构造函数指像谁
 
alert(son.prototype.constructor == girlFriend);//true

再看看实例son1和son的构造函数是否相等
 alert(son1.constructor == son.prototype.constructor);//true
显然也是对的,下面神奇的来了。
 alert(son1.constructor == girlFriend); // true
也是相等的,这就搞不清楚这个孩子是谁生的了,到底是妈生的还是奶生的,这就乱套了是吧!这里的顺序应该是girlFriend为奶奶son这个函数继承了她,然后son是实例son1母亲的层层递进关系,那么我们就应该在给son做prototype继承的时候,重新指向自己的构造函数
 son.prototype.constructor son;

下面我们再弹一下。

 alert(son1.constructor == girlFriend); // false
发现逻辑清楚了,以后我们每次用prototype做继承的时候,紧接着下面就都要把这个对象原型的构造函数指向自己
第三种是直接利用prototype继承
 function girlFriend(){};
 
girlFriend.prototype.mother="柳什么岩";
 
son.prototype=girlFriend.prototype;
 
son.prototype.constructor=son;
 
var son1=new son("张岩","坑爹");
 
alert(son1.mother);// 柳什么岩

同样这也具有继承关系混乱的问题
alert(girlFriend.prototype.constructor);//son
也就是说girlFriend原型的构造函数变成了son,母亲的prototype不找母亲,找她闺女去了。人物关系有点复杂是吧!哈哈
 所以还有第四种,找个中介,代理一下是吧!
 var inter=function(){};
 
inter.prototype=girlFriend.prototype;
 
son.prototype new inter();
 
son.prototype.constructor son;
 
alert(girlFriend.prototype.constructor); // girlFriend

girlFriend和son通过inter来将两个联系在一起,这样一来girlFriend原型的构造函数,就指向自己了
为了使用方便,我们将上面的内容封装成一个函数。
 function extend(Child, Parent) {
     
var inter function(){};
     
inter.prototype = Parent.prototype;
     Child.
prototype new inter();
     Child.
prototype.constructor = Child;

 }

注意这里的父级必须也是有prototype的,也就是说girlFriend要写成:
 function girlFriend(){};
 
girlFriend.prototype.mother="柳什么岩";

 下面我们就可以调用了
 extend(songirlFriend);
 
var son1 new son("张岩","坑爹");
 
alert(son1.mother); // 柳什么岩

js进阶下星期继续。

更多文章请关注公众号:FE学习笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值