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();


 

 

你可能感兴趣的:(继承,javascipt)