創建一個類分兩步走:
第一步:定義構造函數,處理傳入的初始化參數(完成屬性的繼承)
第二步:實現繼承,即增加新的方法。(完成方法的繼承)
示例:
假設我們已有一個Person類,定義如下:
var Person=function(config){
Ext.apply(this,config);
basename="hrch";
baseMethod=function(){alert("a method of base class!")};
};
我們想定義一個Student類,繼承自Person:
/*
*說明:config中也可以包含方法,但最好不要這樣做,新的方法放在第二步中定義。
* /
第一步:定義構造函數,完成初始化
var Student=function(config){
//Student.superclass.constructor這個對象由第二步獲得,沒有第二步,則這個地方會出錯。
Student.superclass.constructor.apply(this,config);//將config中的屬性方法追加到Student對象中。
}
/*
*說明:這里也可以定義新的屬性,但最好不要這樣做,新的屬性放在第一步中定義。
* /
第二步:實現繼承
Ext.extend(Student,Person,{
newMethod1:function(){alert("newMethod1")},
newMethod2:function(){alert("newMethod2")},
});
測試代碼:
<script type="text/javascript">
var Person=function(config){
Ext.apply(this,config);
this.basename="hrch";
this.baseMethod=function(){alert("a method of base class!")};
};
var Student=function(config){
//Student.superclass.constructor這個對象由第二步獲得,沒有第二步,則這個地方會出錯。
Student.superclass.constructor.call(this,config);//將config中的屬性方法追加到Student對象中。
};
Ext.extend(Student,Person,{
newMethod1:function(){alert("newMethod1");},
newMethod2:function(){alert("newMethod2");}
});
var stu=new Student({name:"student",age:"24"});
alert(stu.name);
alert(stu.age);
stu.newMethod1();
stu.newMethod2();
</script>