js的對象之間的繼承拋棄了原型與構造器的概念,而轉為字面量對象之間進行屬性拷貝的方式進行繼承。
首先我們來寫一個封裝好的繼承函數:
function extend(parent){ var child={}; for(var i in parent){ child[i]=parent[i]; } child.uber=parent; return child; }
函數有一個形參parent,函數內部新建一個空的子對象,這個子對象就像一個白的畫板,逐漸的將父對象上的內容臨摹上去。for循環當中是將父對象中的屬性和方法逐個復制給子對象。再將子對象的uber指向父對象,這樣調用子對象的uber屬性就可以調用父對象的屬性和方法了,這相當與java中的super,為什么js當中不用super呢,因為super在js中是保留字,所以采用德語與“super”同義的“uber”來替代。
下面來看看這個函數的實際應用,首先創建一個父對象:
var Shape={ color:"blue", name:"shape", getName:function(){ return this.name; } }
接着我們來實現繼承,並擴展和重寫子對象的一些方法:
var circle=extend(Shape); circle.name="circle"; circle.getName=function(){ return "parentName:"+this.uber.getName()+" childName:"+this.name; } circle.getS=function(){ return this.radius*this.radius*3.14; } circle.init=function(radius){ this.radius=radius; }
首先使用extend函數實現繼承
子對象添加了新的name屬性和新的getName方法,還有擴展的getS方法和init初始化方法
getName中this.uber.getName()調用父對象的getName()方法,得到父對象的name屬性,this.name得到自身的name屬性。
接下來執行方法:
circle.init(5); console.log(circle.name+","+circle.uber.name); console.log(circle.getName()+","+circle.uber.getName()); console.log(circle.getS()); /* 結果: circle,shape parentName:shape childName:circle,shape 78.5 */