第四节 继承
本节是比较java与js如何实现继承
java的类定义包括类和接口。类之间和接口之间可以分别通过extends关键字实现继承。类
和接口不支持多重继承,只能有一个祖先。但一个类可以实现多个接口,这可以理解为一种特
殊的多重继承。无论extends还是implements,都是可以对子类使用instanceof运算符,并返回
为true.
js中没有明确规定的继承机制,这些都是开发者通过模仿实现的。所以有些继承的细节有各种不
同的方式:
1. 对象冒充
父类定义的构造函数使用this关键字给所有属性和方法赋值,子类使父类的构造函数成子类
的方法,然后调用它,将
父类的方法和属性在子类中定义。这里可以实现从多个类多重继承,但如果有同名方法和属性,
后一个的调用的构造函数具有优先性。
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function() {
alert(this.color);
};
}
fuction ClassB(sColor, sName){
this.newMethod = ClassA;
this.newMethod(sColor);
delete this.newMethod;
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
2. call方法
call方法与经典的对象冒充最相似。
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function() {
alert(this.color);
};
}
fuction ClassB(sColor, sName){
//this.newMethod = ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.call(this, sColor);
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
3. apply方法
apply方法与call也相似,只是换用apply()方法,并且使用参数数组
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function() {
alert(this.color);
};
}
fuction ClassB(sColor, sName){
//this.newMethod = ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.apply(this, new Array(sColor));
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
4. 原型链
原型是一种对象模板,能够形成原型链,将父类的所有属性和方法都赋值给子类的实例。这
种方法的弊端是不支持多重继承。并且对于所有子类的实例,instancof父类和子类本身都返回true。
function ClassA(sColor) {
this.color = sColor;
}
ClassA.prototype.sayColor = function () {
alert(this.color);
}
fuction ClassB(sColor, sName){
}
ClassB.prototype = new ClassA();
ClassB.prototype.name = "";
ClassB.prototype.sayName = function(){
alert(this.name);
}
5. 混合方式
使用对象冒充继承父类的属性,使用原型链方式继承父类的方法。
function ClassA(sColor) {
this.color = sColor;
}
ClassA.prototype.sayColor = function () {
alert(this.color);
}
fuction ClassB(sColor, sName){
ClassA.call(this, sColor);
this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function(){
alert(this.name);
}
利用第三方js库zInherit和xbObjects对继承也有一些不错的支持。
JavaScript和java的面向对象 (2)
最新推荐文章于 2021-03-10 13:32:13 发布