在DOJO类中设置和获取对象值的最佳方法

时间:2015-10-19 05:04:34

标签: javascript dojo

我有一个接受对象的类

{ 
    a : "abc",
    b : { z: 'as' }
    c : 123
}

该类需要为对象的属性提供getter和setter函数。

最好的方法是什么?

我应该遵循Java样式和编写器getA/setA / getB/setB函数,还是可以有一个简单的函数或Store来执行此操作?

2 个答案:

答案 0 :(得分:1)

Julian Fondren是一个很好的答案,特别是它适用于JS,而不仅仅适用于DOJO。

如果您需要为custom widget设置getter和setter,则应使用.get()中的.set()dijit/_widgetBase方法,例如。

https://jsfiddle.net/f8pejjy4/2/

require([
    "dojo/_base/declare",
    "dijit/_WidgetBase",
    "dojo/domReady!"
], function (declare, _WidgetBase) {
    var YourWidget = declare(_WidgetBase, {
        a: "",
        _setAAttr: function (value) {
            console.log("Sets value of a to " + value);
            // some custom logic here
            this._set('a', value);
        },
        _getAAttr:function(){
          // some custom logic here
          console.log("Return value");
          return this.a;
        },
    });

    var yourWidget = new YourWidget().placeAt(document.body);
    yourWidget.startup();


    yourWidget.set('a', 'another value');
    yourWidget.get('a');
});

答案 1 :(得分:0)

无需使用getA / setA函数。

var x = {
  _a: "a",
  set a(x) { this._a = x },
  get a(x) { return this._a + "bc" },
  b: { z: "as" },
  get c() { return 123 }
}

console.log(x.a)
x.a = 'x'
console.log(x.a)
console.log(x.c)
x.c = 1
console.log(x.c)

输出:

abc
xbc
123
123

JavaScript的getter和setter具有作为事后想法工作的优势。当您决定需要它们时,可以添加它们,代码可以保持与访问的相同并设置对象的成员。

如果假私有_a是不可接受的,你可以通过让getter和setter函数靠近它来使它实际上是私有的:

var x = (function() {
  var secret = 2
  return {
    get a() { return secret }
  }
})()
/* no way to access 'secret' here */