1

我正在尝试找出使用原型设置 JavaScript 对象字段的正确方法。

我可以使用以下内容:

function myData() {};
myData.prototype.a = null;
myData.prototype.b = null;
myData.prototype.c = null;

var data = new myData();
data.a = 1;
data.b = 2;
data.c = 3;

但是,这似乎没有遵循适当的封装协议。

或者,我可以这样做:

function myData() {
    this._a = null;
    this._b = null;
    this._c = null;
};

myData.prototype.__defineGetter__("a", function() {
    return this._a;
});

myData.prototype.__defineSetter__("a", function(val) {
        this._a = val;
});

当我的 getter 只是返回私有变量的值而不用它做任何事情时,这种方法似乎有点矫枉过正。

另外,如果我直到稍后才拥有这些值,那么在构造函数中将值设置为 null 是否正确?即 - 我稍后设置它们。

4

2 回答 2

3

JavaScript 是一种动态语言,如果您严格不需要封装那些您不必封装的属性。因此,第一个例子非常好。

否则,如果您需要封装它们,并且您处于符合 ES5 的环境中,则应该使用getand set,因为__defineGetter__and__defineSetter__已被弃用且不标准(请参阅:https ://developer.mozilla.org/en/JavaScript/Reference/ Global_Objects/Object/DefineGetterhttps://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_getters_and_setters

一个例子:

function MyData() {
    // set to the prototype's value
    var a = this.a;
    var b = this.b;
    var c = this.c;

    Object.defineProperties(this, { 
        "a": {
            get : function(){ return a; },
            set : function(value) { a = value }
         },
         "b": {
            get : function(){ return b; },
            set : function(value) { b = value }
         },
         "c": {
            get : function(){ return c; },
            set : function(value) { c = value }
         }
    });
};

MyData.prototype.a = null;
MyData.prototype.b = null;
MyData.prototype.c = null;

请参见Object.defineProperties

于 2012-06-06T01:18:44.663 回答
0

am trying to figure out the proper way to set up fields of my JavaScript object

You should define what you mean by "proper".

>  var data = new myData();
>  data.a = 1;
>  data.b = 2;
>  data.c = 3; 

In the above, you are adding a, b and c properties to the data object, you aren't modifying the value of myData.prototype.a (i.e. data[[Prototype]].a), etc.

But, this does not seem to follow proper protocol for encapsulation.

You should explain what you mean by that, i.e., what you think the above should achieve.

[ snip __defineGetter__, __defineSetter__ code ]

This method seems overkill when my getters are just returning the private variable's value

"Private" variables, in the classic sense, don't exist in ECMAScript. You can emulate them with closures though. Have a look at the module pattern.

于 2012-06-06T02:10:12.767 回答