在ES5 中,js 的继承主要分为以下几类:
- 类式继承
function fFatherClass(){};
fFatherClass.prototype.fAlert = function{
alert(hello,i'am father class);
}
function fChildClass(){};
fChildClass.prototype = new fFatherClass();
fChildClass.prototype.fChildOwnFunc = function(){//code}
//因为是引用原型链的,所以缺点是一个子类修改了父类的方法或属性,那么对其它子类也会产生影响
- 构造函数继承
function fFatherClass(){
this.name = 'fatherClass';
};
fFatherClass.prototype.fAlert = function{
alert(hello,i'am father class);
}
function fChildClass(){
fFatherClass.call(this);
}
//但是这样继承有一个缺点,就是只能继承父类在构造函数中的方法与属性,不能继承原型链上的方法与属性
- 组合继承
function fFatherClass(){
this.name = 'fatherClass';
};
fFatherClass.prototype.fAlert = function{
alert(hello,i'am father class);
}
function fChildClass(){
fFatherClass.call(this);
}
fChildClass.prototype = new fFatherClass();
- 原型式继承
var oFather = {
//function
//var
}
var oChild = inheritObject(oFather);
//然后就可以给子类添加自己的方法与属性了
- 寄生式继承
var oFather = {
//function
//var
}
var createChild(oFather){
var o = inheritObject(oFather);
o.childOwnFunc = function(){}
return o;
}
- 寄生组合式继承
function oFatherClass(){
//var
}
oFatherClass.prototype.oFatherPrototypeFunction = function(){};
function oChildClass(){
oFatherClass.call(this);
this.childVar = value;
}
inheritPrototype(oChildClass,oFatherClass);
oChildClass.prototype.childOwnChildFunction = function(){};