1.組合繼承####
使用原型鏈繼承超類的函數(shù),利用構(gòu)造函數(shù)繼承超類的屬性。
function Super(name){
this.name=name,
this.colors = ['yellow','blue','green'],
}
Super.prototype.sayName = function(){
alert(this.name);
}
function Sub(name,age){
Super.call(this,'Json');
}
Sub.prototype = new Super();
Sub.prototype.constructor = Sub;
2.原型式繼承
function object(o){
function F(){}
F.prototype = o;
return new F();
}
可以使用ECMAScript5的Object.create()(第一個參數(shù)傳用作新對象原型的對象到涂,第二個傳新對象的額外屬性)
3.寄生式繼承(即創(chuàng)建一個封裝繼承過程的函數(shù))
function createOther(o){
var clone = Object.create(o);
clone.sayName = function () {
alert('hello');
}
return clone
}
4.寄生式組合繼承(避免組合繼承兩次調(diào)用超類構(gòu)造函數(shù)的性能問題鞭盟,避免在原型上添加不必要的屬性和方法)
function inherit(Sub,Super){
var pro = Object.create(Super.prototype);
pro.constructor = Sub;
Sub.prototype = pro;
}
function Super(name){
this.name=name,
this.colors = ['yellow','blue','green'],
}
Super.prototype.sayName = function(){
alert(this.name);
}
function Sub(name,age){
Super.call(this,'Json');
}
inherit(Sub,Super);