javascript如何实现继承

javascript实现继承,其实就是实现三层含义:
1.子类的实例可以共享父类的方法。
2.子类可以覆盖父类的方法或者扩展新的方法。
3.子类和父类都是子类实例的“类型”。

使用原型继承,中间使用临时对象作为Child的原型属性,临时对象的原型属性再指向父类的原型,防止所有子类和父类原型属性都指向同一个对象,这样当修改子类的原型属性,就不会影响其他子类和父类。

function extend(Child,Parent){
    var F=function(){};
    F.prototype=Parent.prototype;
    Child.prototype.constructor=Child;
    Child.base=Parent.prototype;
}
function Parent(name){
    this.aa=123;
    this.getName=function(){
        return name;
    } //使用闭包模拟私有成员
    this.setName=function(value){
        name=value;
    };
}
Parent.prototype.print=function(){alert("print!");};
Parent.prototype.hello=function(){
    alert(this.getName()+"Parent")
};
function Child(name,age){
    Parent.apply(this,arguments); //调用父类构造函数来继承父类定义的属性
    this.age=age;
}
extend(Child,Parent); //继承Parent

Child.prototype.hello=function(){ //重写父类hello方法
    alert(this.getName()+"Child");
    Parent.prototype.hello.apply(this,arguments); //调用父类同名方法
};
//子类方法
Child.prototype.doSomething=function(){
    alert(this.age+"Child doSomething");
};
var p1=new Child("xhan",22);
var p2=new Child("xxx",33);
p1.hello();
p2.hello();
p1.doSomething(); //子类方法
p1.print(); //父类方法

alert(p1 instanceof Child); //true
alert(p1 instanceof Parent); //true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值