3

我不确定我是否做对了。

这个例子直接来自 MDN(Mozilla 开发者网络):

var bValue;  
Object.defineProperty(o, "b", {get : function(){ return bValue; },  
                               set : function(newValue){ bValue = newValue; },  
                               enumerable : true,  
                               configurable : true});  

发生的事情是 - 它创建了一个名为 bValue 的全局变量,但没有完成。我知道这个例子只演示了使用,因此如果它创建一个全局变量是可以的。但是如果我要在应用程序中使用它,我会稍微修改它,添加this关键字:

Object.defineProperty(o, "b", {get : function(){ return this.bValue; },  
                               set : function(newValue){ this.bValue = newValue; },  
                               enumerable : true,  
                               configurable : true}); 

现在,该对象o将具有 property b,同时,它还将具有另一个 property bValue。用户(程序员)将只接触到“b”而不接触“bValue”,尽管他仍然可以直接访问 bValue——我不知道如何防止它。

我知道属性b和属性bValue可能并不总是相同,而是b取决于值,bValue因为 getter 和 setter 允许我们在将值分配给之前对 bValue 进行预处理b

主要问题是,我做对了吗?或者我在这里错过了什么?

4

2 回答 2

6

你似乎在寻找一个关闭。这是一种编码模式,使您能够使用私有变量并仅公开您想要公开的内容(公共变量)。

(function() {
    var bValue;

    Object.defineProperty(o, "b", {get : function(){ return bValue; },  
                                   set : function(newValue){ bValue = newValue; },  
                                   enumerable : true,  
                                   configurable : true}); 
})();

它创建一个函数并立即执行它。这似乎没用,但由于函数引入了一定程度的作用域bValue因此只能在函数内以这种方式访问​​。

o.b属性充当开发人员和值之间的委托。您无法访问bValue自己。(虽然在这个例子中,getter/setter 的行为显然与直接使用完全一样bValue。)

http://jsfiddle.net/W4CSE/2/

于 2012-01-03T13:51:51.050 回答
3

这个想法是将代码包装在一个闭包中,从而隐藏bValue在世界之外,如下所示:

var o =(function() {

    var o={},bValue;    

   Object.defineProperty(o, "b", {get : function(){ return bValue; },  
                               set : function(newValue){ bValue = newValue; },  
                               enumerable : true,  
                               configurable : true});


    return o;

})();

现在你可以参考o.b但不能bValue

于 2012-01-03T13:52:53.977 回答