【问题标题】:I'm changing the constructor of a javascript class, but the new constructor isn't called?我正在更改 javascript 类的构造函数,但没有调用新的构造函数?
【发布时间】:2014-03-12 03:21:33
【问题描述】:

我正在使用 SAP UI5 框架。我正在创建一个类的实例,然后更改一个类的构造函数。在创建类的第二个实例时,不会调用新的构造函数!

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

谢谢

【问题讨论】:

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

标签: javascript javascript-framework sapui5


【解决方案1】:

您实际上并没有通过这样做来更改构造函数

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;

【讨论】:

    【解决方案2】:

    更改默认构造函数会影响对象行为,所以不要这样做。

    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 2019-03-14
      • 1970-01-01
      相关资源
      最近更新 更多