2014-02-13 46 views
0

我正在使用SAP UI5框架。我正在創建一個類的實例,然後更改一個類的構造函數。在創建類的第二個實例時,不會調用新的構造器!我正在改變一個JavaScript類的構造函數,但新的構造函數不被調用?

var myConstructor = function(){ 
    alert('my own constructor'); 
} 
var btn = new sap.m.Button({text:'Hello World'}) //sap.m.Button is a class 
sap.m.Button.prototype.constructor = myConstructor; //Changing the constrcutor 
var btn2 = new sap.m.Button({text:'h'}); // why myConstructor aint called ! 

這裏是工作示例http://jsbin.com/voluc/2/edit

感謝

+0

'var btn2 = new btn.constructor({text:'h'})'' – elclanrs

回答

2

你沒有真正做這個

sap.m.Button.prototype.constructor = myConstructor; 

你簡單地改變時使用的特性改變構造通過原型來引用它的構造函數。

完全改變你只需要構造重新分配它

sap.m.Button = myConstructor; 

不過我不知道爲什麼要這麼做。如果您想臨時更改構造函數,那麼您可能需要先存儲它,然後將其重新設置爲初始版本。

var oldCtor = sap.m.Button; 
sap.m.Button = = myConstructor; 
// finished doing your tasks 
sap.m.Button = oldCtor; 
1

更改默認的構造函數會影響對象的行爲,所以不要這樣做。

<script> 
    var myConstructor = function(){ 
     alert('my own constructor'); 
    } 
    var btn = new sap.m.Button({text:'Hello World'}) 
    btn.placeAt('content'); 
    sap.m.Button = myConstructor; //Changing the constrcutor 
    var btn2 = new sap.m.Button({text:'h'}); // why myConstructor ain't called ! 

    console.log(sap.m.Button.constructor) 
    //but if you see i doh't write btn2.placeAt("content") because of your constructor don't do many things as need 


</script> 
相關問題