在JS开发中,使用继承,可以使代码更便于维护,减少代码量。
JS继承的方法有许多,我在这里列举一下我所知道的集成方法
一、对象冒充
1、mb只能继承ma的局部(私有)的属性或方法,对于ma的原型变量或方法(使用 ma.prototype 定义的)是无法继承的。
2、对象冒充可以实现多重集成,即mb可以继承多个对象。
二、call()或者apply()方法
1、call()的第二个参数可以是任意类型,而apply()的第二个参数必须是数组,也可以是arguments
2、mb只能继承ma的局部(私有)的属性或方法,对于ma的原型变量或方法(使用 ma.prototype 定义的)是无法继承的。
三、原型链(prototype chaining)
1、使用原型链(prototype chaining)继承,子对象完全继承父对象的所有属性和方法,包括但不限于父对象的局部变量、局部方法、原型变量、原型方法。
JS继承的方法有许多,我在这里列举一下我所知道的集成方法
一、对象冒充
示例代码如下所示:
function ma(name){
this.name=name; //无论在ma,还是其子类mb中都能进行调用
var maName=name; //maName只能在ma中调用,无法在其子类mb中调用
this.maShow=function(){
console.log("我的名字是:"+maName+"运行在ma方法中");
}
}
function mb(name,age){
this.demoMethod=ma; //这里this的属性随便定义,例如this.newMethod,都是可以的
this.demoMethod(name);
delete this.demoMethod;
this.age=age;
this.mbShow=function(){
console.log("我的名字是"+this.name+",今年:"+this.age+",运行在mb方法中"); //正确
console.log("我的名字是"+maName+",今年:"+this.age+",运行在mb方法中"); //错误,无法调用父类ma的私有变量maName
}
}
var demo=new mb('xyong',25);
demo.maShow(); //正确,可以这样调用ma中的私有变量maName
demo.mbShow();
备注:1、mb只能继承ma的局部(私有)的属性或方法,对于ma的原型变量或方法(使用 ma.prototype 定义的)是无法继承的。
2、对象冒充可以实现多重集成,即mb可以继承多个对象。
二、call()或者apply()方法
function ma(name,age){
this.name=name;
this.maShow=function(){
console.log("我的名字是:"+this.name+"运行在ma方法中,今年:"+this.age);
}
}
function mb(name,age){
this.age=age;
ma.call(this,name,age); //使用call方法
//ma.apply(this,[name,age]); //使用apply方法,第二个参数为数组
//ma.apply(this,arguments); //使用apply方法,第二个参数为arguments
this.mbShow=function(){
console.log("我的名字是"+this.name+",今年:"+this.age+",运行在mb方法中");
}
}
var demo=new mb('xyong',25);
demo.ma();
demo.mbShow();备注:1、call()的第二个参数可以是任意类型,而apply()的第二个参数必须是数组,也可以是arguments
2、mb只能继承ma的局部(私有)的属性或方法,对于ma的原型变量或方法(使用 ma.prototype 定义的)是无法继承的。
三、原型链(prototype chaining)
function ma(){
this.age=25;
this.showage=function(){
console.log("测试的年龄是:"+this.age);
}
}
ma.prototype.name="test";
ma.prototype.maShow=function(){
console.log("我的名字是:"+this.name);
};
function mb(){
}
mb.prototype=new ma();
mb.prototype.address="";
mb.prototype.mbShow=function(){
console.log("我的地址是:"+this.address);
}
var demoma=new ma();
var demomb=new mb();
demoma.name='测试姓名ma';
demomb.name='测试姓名mb';
demomb.address="测试地址mb";
demoma.maShow();
demomb.maShow();
demomb.mbShow();
console.log(demomb instanceof ma);
console.log(demomb instanceof mb);
console.log("ma年龄是:"+demoma.age);
console.log("mb年龄是:"+demomb.age);
demoma.showage();
demomb.showage();备注:1、使用原型链(prototype chaining)继承,子对象完全继承父对象的所有属性和方法,包括但不限于父对象的局部变量、局部方法、原型变量、原型方法。
本文介绍了JavaScript中的三种继承方法:对象冒充、call/apply方法及原型链。详细讲解了每种方法的实现原理、特点及限制,并通过示例代码帮助读者理解。
273

被折叠的 条评论
为什么被折叠?



