【问题标题】:How Javascript Class property are made unaccessible?如何使 Javascript 类属性无法访问?
【发布时间】:2014-03-12 02:00:42
【问题描述】:

我正在使用框架 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 是未定义的?类是如何实现的,不能直接访问属性,只能通过类提供的方法访问?

【问题讨论】:

  • 很可能他们存储你传递给构造函数的选项对象是一些伪私有成员,然后用于访问文本属性

标签: javascript javascript-framework sapui5


【解决方案1】:

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

myButton.mProperties.text

【讨论】:

【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    您在这里所做的是将一个对象传递给类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"
    

    【讨论】:

    • 为什么有人要在每个实例上定义一个共享方法?这根本不是一个好习惯。
    【解决方案4】:

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

    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"
    

    【讨论】:

    • 正确但效率不高。在每个实例上单独定义共享成员是一种不好的做法。
    • 这只是一个例子))
    • 是的,但这确实是一种做法;应该避免
    • 您能否提供链接以提高我对这一点的了解,好的做法?
    • 只要阅读与 JavaScript 中的原型链机制有关的任何内容。
    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 2014-11-21
    • 2018-09-13
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2015-11-21
    相关资源
    最近更新 更多