javascipt 实现继承

//使用 call /apply实现继承,此方法针对父类中所有方法都不是以原型的方式实现的
function person(name,age){
    this.name=name;
    this.age=age;

    this.show = function(){
        console.log("call person   name:"+this.name+" age:"+this.age);
    }
}

function student(name,age,grade){
    person.call(this,name,age);

    this.grade = grade;
}

student.prototype.showGrade = function(){
    console.log("student call: grade:"+this.grade);
};


var stu = new student("zjw",24,1);
stu.show();
stu.showGrade();


 

 

 

//使用对象冒充实现继承
function person(name,age){
    this.name=name;
    this.age=age;

    this.show = function(){
        console.log("call person   name:"+this.name+" age:"+this.age);
    }
}

function student(name,age,grade){
    this.person=person;
    this.person(name,age);
    delete  this.person;

    this.grade=grade;

    this.showGrade = function(){
        console.log("student call: grade:"+this.grade);
    }
}

var stu = new student("zjw",24,1);
stu.show();
stu.showGrade();


 

 

 

 

//使用原型拷贝实现继承,这是最好的方式

function person(name,age){
    this.name=name;
    this.age = age;

    this.show1 = function(){
        console.log("person show1 call: name:"+this.name+" age:"+this.age);
    }
}

person.prototype.show2 = function(){
    console.log("person show2 call: name:"+this.name+" age:"+this.age);
};

function student(name,age,grade){

    person.call(this,name,age);//拷贝name age show1


    var prop;
    //复制父类的以原型实现的方法
    for (prop in person.prototype) {
        var proto = this.constructor.prototype;

        if (!proto[prop]) {
            proto[prop] = person.prototype[prop];
        }

        proto[prop]["super"] = person.prototype;
    }

    this.grade=grade;
}

student.prototype.show = function(){
    console.log("student show call: name:"+this.name+" age:"+this.age+" grade:"+this.grade);
};

var stu = new student("zjw",24,1);
stu.show1();
stu.show2();
stu.show();


 

方法4:



function person(name,age,obj){

    console.log("person call"+arguments.length);
    this.name = name;
    this.age = age;

    this.obj = obj;

    this.method1 = function(){
        console.log("method1 call:"+this.name+"--"+this.age+"---"+this.obj);
    }
}

person.prototype.method2 = function(){
    console.log("method2 call:"+this.name+"---"+this.age+"---"+this.obj);
};


function student(name,age,grade,obj){
    person.call(this,name,age,obj);

}



function inherits(curClass,parentClass){
    curClass.prototype = new parentClass();
}

inherits(student,person);


var stu1 = new student("zjw",24,1,[1,2,3]);
stu1.method1();
stu1.method2();


 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值