資源描述:
《詳解extextend的使用方法》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、extend?(Objectsubclass,Objectsuperclass,[Objectoverrides]:Object?第一個(gè)參數(shù):子類?第二個(gè)參數(shù):父類?第三個(gè)參數(shù):要覆蓋的屬性。?這里需要強(qiáng)調(diào)一下,子類繼承下來的是父類中通過superclass.prototype方式定義的屬性(包括用此方法定義的函數(shù))。使用方式使用示例假設(shè)有個(gè)?function?名為?SuperClass?,要實(shí)現(xiàn)一個(gè)子類,名為?MyClass?。下面的兩種方式都可以實(shí)現(xiàn)這個(gè)功能。MyClass?=?Ext?.?extend?(?SuperCl
2、ass?,?{?/**/?});Ext?.?extend?(?MyClass?,?SuperClass?,?{?/**/?});?下面來個(gè)具體示例:var?a?=?function?(?id?){????this?.?id?=?id?;}a?.?prototype?=?{????tostring?:?function?(){????????return?this?.?id?;????}};???????????b?=?function?(?id?){????b?.?superclass?.?constructor?.?call
3、?(?this?,?id?);}Ext?.?extend?(?b?,?a?,?{????tostring?:?function?(){????????return?String?.?format?(?"b:{0}"?,?this?.?id?);????}});//?測(cè)試一下var?obj1?=?new?a?(?"obj1"?);alert?(?obj1?.?tostring?());var?obj2?=?new?b?(?"obj2"?);alert?(?obj2?.?tostring?());或者下面的代碼,可以得到同樣的效果
4、:var?a?=?function?(?id?){????this?.?id?=?id?;}a?.?prototype?=?{????tostring?:?function?(){???????return?this?.?id?;????}};?b?=?Ext?.?extend?(?a?,?{????tostring?:?function?(){???????return?String?.?format?(?"b:{0}"?,?this?.?id?);????}});//?測(cè)試一下var?obj1?=?new?a?(?"obj
5、1"?);alert?(?obj1?.?tostring?());var?obj2?=?new?b?(?"obj2"?);alert?(?obj2?.?tostring?());?一個(gè)錯(cuò)誤例子下面看個(gè)示例:BaseClass?=?function?()?{????this?.?f1?=?function?()?{????????alert?(?"f1inbase"?);????}?????this?.?f2?=?function?()?{????????alert?(?"f2inbase"?);????}}?ChildClas
6、s?=?function?()?{??ChildClass?.?superclass?.?constructor?.?call?(?this?);}????????Ext?.?extend?(?ChildClass?,?BaseClass?,?{????f1?:?function?()?{????????alert?(?"f1inchild"?);????},?????f3?:?function?()?{????????alert?(?"f3inchild"?);????}});?var?b?=?new?ChildClass?
7、();b?.?f1?();b?.?f2?();b?.?f3?();?可以去執(zhí)行一下,可以發(fā)現(xiàn)?f1?的執(zhí)行結(jié)果仍然是?"f1inbase"?。并沒有真正的達(dá)到?override?的效果。?Ext.extendputsthepropertiesspecifiedinthe3rdargumentintothe?subclass's?prototype?也就是說:第三個(gè)參數(shù)里面的函數(shù)被放置在了子類的?prototype?中。而在?ChildClass.superclass.constructor.call(this);?這句上,?B
8、aseClass?的?f1?成了?ChildClass?的變量,而不是?ChildClass.prototype?。通過對(duì)?JavaScript?的原型繼承的了解,可以知道,實(shí)例變量的優(yōu)先級(jí)是高于?prototype?的,所以上面的這個(gè)代碼是達(dá)不到?override?的功能的