之前在教學視頻有看過javascript的call。這個方法在ExtJs中是很常用的。
以前在搞ExtJs的時候總是忽略initComponent里面的一句代碼,如下所示。今天在看其他人代碼的時候發現調用的函數和自己想像的不一樣。所以認真看了一下代碼,再結合之前js關于call的筆記。知道了其中的原因
Son.superclass.initComponent.call(this);
這里的call就是調用"Son"父類的initComponent函數,并把this傳進去,這個this是Son的實例對象。
下面用一個js代碼解釋一下這個call 是怎樣的
function Dog(name){
this.name = name;
}
function test(){
alert(this.name);
}
var dog = new Dog('lil');
test.call(dog);//這句話相當于dog.test();所以test()里面的this是dog,即this.name是dog.name,即彈出'lil'
如上面代碼所示,test.call(dog)等價于dog.test();
下面舉ExtJs代碼的例子
Son = Ext.extend(Father,{
initComponent : function() { Son.superclass.initComponent.call(this);//這里調用父類的initComponent方法,即Father的initComponent方法,并把this,Son的實例對象做為參數傳過去 },
test : function() {
alert('test in Son');
}
}
Father = Ext.extend(Ext.Panel,{
initComponent : function() { Father.superclass.initComponent.call(this);
this.test();//這里的this是Son的實例對象,相當于Son son = new Son();son.test();
//所以調用的是子類的test方法而不是父類的test方法,我之前以為是調用父類的test方法
},
test : function() {
alert('test in Father');
}
}