Pergunta

I'm using the framework SAP UI5. I'm creating an instance of a class

//sap.m.Button is a javascript class

var myButton = new sap.m.Button({text:"Hello"});
console.log(myButton.getText());             //Hello
console.log(myButton.getProperty('text');    //Hello
console.log(myButton.text);                  //undefined

Why myButton.text is undefined ? How is the class implemented such that property cannot be accessed directly rather only by the methods provided by the class ?

Foi útil?

Solução 2

It's more likely that they store the options variable as an instance property, and define the methods on the prototype of the constructor.

function Button(opts){
     this.opts = opts;
}

Button.prototype = {
    constructor: Button,
    getText: function() { return this.opts.text; }
}

Outras dicas

You can hide the property of object by doing this for example

var button = function(opts){
  /* private data */
  var text = opts.text;

  this.getText = function(){
    return text;
  }
}

var bb = new button({ text: "Hello" });
// bb.text == undefined
// bb.getText() == "Hello"

What you do here is pass an object to the constructor of the class sap.m.Button. What happens with that object in the constructor is up to the implementation. It doesn't necessarily has to add them to the object. In this case they are likely stored in a local variable of the object. The constructor likely looks something like this:

sap.m.Button = function(properties) {
    var text = properties.text; // private variable only visible in the scope of the class

    this.getProperty(key) { // public function - as denoted by the prefix "this."
        if (key == 'text') {
            return text;  // returns the value of the private variable
        }
        // ... and more code for other properties ...
    }

    // ... and much more stuff ....
}

But you can add public variables to an object later:

var myButton = new sap.m.Button({text:"Hello"});
myButton.myVariable = "foo";
colsole.log(myButton.myVariable); // outputs "foo"

Properties of a managed object should only be accessed via the mutator or accessors provided eg getText, if you really want to access them directly try

myButton.mProperties.text
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top