1

我正在使用框架 SAP UI5。我正在创建一个类的实例

//sap.m.Button 是一个javascript类

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

为什么 myButton.text 未定义?类是如何实现的,以至于不能直接访问属性,而只能通过类提供的方法来访问?

4

4 回答 4

2

例如,您可以通过这样做来隐藏对象的属性

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"
于 2014-02-13T09:32:09.133 回答
1

您在这里所做的是将对象传递给类的构造函数sap.m.Button。该对象在构造函数中会发生什么取决于实现。它不一定必须将它们添加到对象中。在这种情况下,它们可能存储在对象的局部变量中。构造函数可能看起来像这样:

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

但是您可以稍后将公共变量添加到对象:

var myButton = new sap.m.Button({text:"Hello"});
myButton.myVariable = "foo";
colsole.log(myButton.myVariable); // outputs "foo"
于 2014-02-13T09:35:31.360 回答
1

他们更有可能将 options 变量存储为实例属性,并在构造函数的原型上定义方法。

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

Button.prototype = {
    constructor: Button,
    getText: function() { return this.opts.text; }
}
于 2014-02-13T09:46:57.100 回答
1

托管对象的属性只能通过提供的 mutator 或访问器访问,例如getText,如果您真的想直接访问它们,请尝试

myButton.mProperties.text
于 2014-02-14T01:49:16.107 回答