js实现模拟继承的方法

1.通过拓展Object类的原型对象实现继承

    function Parent(name,age,ID,address){

    this.name = name;
this.age = age;
this.id = ID;
this.address = address;
}

function Child(school){
this.school = school;
}
Object.prototype.extend = function(parentObj){
for(var i in parentObj){
this[i] = parentObj[i];
}
};

var parent = new Parent("小明","24","10001","福山");
var child = new Child("长江大学");
child.extend(parent);//子类继承父类
console.log(child.age);

2.通过call方法改变指针指向实现继承
//call无参的
function parent2(){
this.name = "zhangsan";
this.age = 20;
}
function child2(){
console.log(this.name+" "+this.age);
}
var p = new parent2();

//child2();//window对象调用该方法
//p.show();//写法错误,因为p对象没有show方法
child2.call(p);//这种写法可以实现让show方法里的this指向p对象


//call有参的
function parent3(){
this.name = "zhangsan";
this.age = 20;
}
function child3(school){
console.log(this.name+" "+this.age+":"+school);
}
var p1 = new parent3();
child3.call(p1,"长江大学");//这种写法可以实现让show方法里的this指向p对象
 
3.通过apply方法改变指针指向实现继承

//apply无参的
function parent4(){
this.name = "xiaohong";
this.age = 25;
}
function child4(){
console.log(this.name+" "+this.age);
}
var p2 = new parent4;
child4.apply(p2);

//apply有参的
function parent5(){
this.name = "xiaohong";
this.age = 25;
}
function child5(school){
console.log(this.name+" "+this.age+" "+school);
}
var p3 = new parent5;
child5.apply(p3,['长江大学']);


4.通过改变对象的prototype方法实现继承

function Parent6(address,net,no){
this.add = address;
this.net = net;
this.no = no;
}
function Child6(school,teacher){
this.school = school;
this.teacher = teacher;
}
Child6.prototype = new Parent6("迎春大街","www.jerui.com","1608");
var child6 = new Child6();
console.log(child6.add);
 



原文地址:https://www.cnblogs.com/chencuixin/p/6485533.html