javascript 继承之拷贝,原型,类式

// 拷贝继承,在子类内调用父类并修正this指向,再通过for in 拷贝父类的方法实现继承,具体实现如下代码 :
function Tab(){//父类构造函数
this.name='aaa';
this.age=20;
}
Tab.prototype.init = function(){
alert(this.name);
};
function Child(){//子类构造函数
Tab.call(this);//在子类构造函数内调用父类,使子类继承父类的属性
}

for(var attr in Tab.prototype){//通过for in 拷贝父类原型上的方法
Child.prototype[attr]=Tab.prototype[attr];
}
var child=new Child();
var tab=new Tab();
child.name="bbb";//这里我们修改了子类的属性,下面打印结果,修改了子类不会影响父类
console.log(tab)
console.log(child)

console.log(child instanceof Tab);//false
console.log(child instanceof Child);//true 看出,child的构造函数还是自己本身

 

//原型继承,在子类的原型上继承父类的实例化对象 :

 

var father=function(){
this.name='aa';
}
father.prototype.a=function(){
alert(this.name);
}
var child=function(){}

var fa=new father();

child.prototype=fa;//在子类的原型上继承父类这个对象

var man=new child();
man.name='bbb';
fa.name="ccc";
console.log(fa);
console.log(man);//继承的属性和值在其原型链上
alert(fa.name)//ccc
alert(man.name)//bbb

//类式继承,通过在子类的构造函数类调用父类的构造函数,使子类拥有父类的属性和方法,并通过call或apply改变this指向,来实现继承 : 

var father=function(){
this.name='aa';

this.age=function(){alert(1)}
}
father.prototype.a=function(){
alert(this.name);
}
var child=function(){
father.call(this);
}

child.prototype=father.prototype;//继承父类的方法

var f=new father();
var c=new child();
console.log(f);
console.log(c);



转载于:https://www.cnblogs.com/week-1/p/6553650.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值