Pergunta

I'm using SAP UI5 Framework. I'm creating an instance of a class and then changing the constructor of a class. While creating the second instance of the class, new constrctor isn't called!

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 !

Here is the working example http://jsbin.com/voluc/2/edit

Thanks

Foi útil?

Solução

You're not actually changing the constructor by doing this

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

You're simply changing a property that is used by the prototype to refer back to it's constructor function.

To completely change the constructor you simply need to re-assign it

sap.m.Button = myConstructor;

Still I don't know why you would do that. If you want to temporarily change the constructor then you might want to store it first and then set it back to it's initial version.

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

Outras dicas

Changing default constructor can affects on object behaviour so don't do that things.

<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>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top