1.apply方法
apply方法详情可以参考JavaScript中的apply和call
apply方法同样也可以实现多继承
示例代码
function School(){
this.name = 'HEU';
this.showName = function(){
console.log(this.name);
}
}
function Unit(){
this.uname = 'meituan.com';
this.showUname = function(){
console.log(this.uname);
}
}
function Applyer(){
//apply方法继承School类和Unit类
School.apply(this, arguments);
Unit.apply(this, arguments);
}
var me = new Applyer();
me.showName();
me.showUname();
运行结果
apply语句分别用School和Unit替代了Applyer中的this,成功的实现了继承
也可以用call方法来实现
2.原型链方法
prototype对象是一个模板,要实例化的对象都以这个模板为基础,简单地说,意思就是prototype对象的任何属性和方法,都被传递给那个类的所有实例,原型链方法使用这种功能来实现继承。
prototype的相关知识可以参考JavaScript中的对象与类
示例代码
function Box(){
this.size = 2;
this.showSize = function(){
console.log('the size is ' + this.size);
};
}
function Package(){
}
Package.prototype = new Box();
var pack = new Package();
pack.showSize();
运行结果
在以上的代码中,想要让Package继承Box的所有属性和方法,我们把Package的prototype属性设置为Box的实例
注意:原型链不能实现多重继承!
我们可以利用instanceof方法来确定原型和实例之间的关系
实例代码
function Box(){
this.size = 2;
this.showSize = function(){
console.log('the size is ' + this.size);
};
}
function Box2(){
}
function Package(){
}
Package.prototype = new Box();
var pack = new Package();
pack.showSize();
console.log(pack instanceof Box);
console.log(pack instanceof Package);
console.log(pack instanceof Box2);
运行结果
3.混合方式
创建类的最好方式是用构造函数定义属性,用原型定义方法,这种方法同样适合于继承机制。
示例代码
function Fruit(season, weight){
this.season = season;
this.weight = weight;
}
Fruit.prototype.showMessage = function(){
console.log(this.season);
console.log(this.weight);
};
function Apple(season, weight, size){
Fruit.call(this, season, weight);
this.size = size;
}
Apple.prototype = new Fruit();
Apple.prototype.showMessage2 = function(){
console.log(this.season);
console.log(this.weight);
console.log(this.size);
};
var apple = new Apple('spring', 3, 2);
var pear = new Fruit('summer', 4);
apple.showMessage();
console.log('\n');
apple.showMessage2();
console.log('\n');
pear.showMessage();
//用instanceof进行测试 观察
console.log('\n');
console.log(pear instanceof Fruit);
console.log(pear instanceof Apple);
console.log(apple instanceof Apple);
console.log(apple instanceof Fruit);
运行结果