继承是面向对象程序设计中的重要部分,javaScript 实现继承的方式不止一种。这是因为 JavaScript 中的继承机制并不是明确规定的,而是通过模仿实现的.
1.对象冒充
可以实现,多重继承。新属性要写在delete后面。
function classA(sId)
{ this.id=sId;
this.showId=function(){alert(this.id)}
}
function classB(sId,sName)
{
this.newMethod=classA;
this.newMethod(sId);
delete this.newMethod;//继承classA
this.name=sName;
this.showName=function()
{alert(this.name)}
}
如上例将有newMethod的三行换成, classA.call(this, sId) 或 classA(this, new Array(sId)) ;就可以实现继承。
3、原型链
原型链最大的缺点是不能传递参数。
function classA(){
}
classA.prototype.id="4";
classA.prototype.showId=function(){ alert(this.id); }
function classB(){}
classB.prototype=new classA();
var b=new classB();
var a=new classA();
a.showId();
b.showId();
与对象冒充相似,子类的所有属性和方法都必须出现在 prototype 属性被赋值后,因为在它之前赋值的所有方法都会被删除。为什么?因为 prototype 属性被替换成了新对象,添加了新方法的原始对象将被销毁。所以,为 ClassB 类添加 name 属性和 showName() 方法的代码如下:
function ClassB() {
}
ClassB.prototype = new ClassA();
ClassB.prototype.name = "";
ClassB.prototype.showName = function () {
alert(this.name);
};
4.混合方式
对属性用Call, 对方法用prototype.
function ClassA(sId) {
this.id = sId;
}
ClassA.prototype.showId = function () {
alert(this.id);
};
function ClassB(sId, sName) {
ClassA.call(this, sColor);
this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.showName = function () {
alert(this.name);
};
参考图书:<<javascript高级程序设计>>