Javascript私有变量+ Object.create(对闭包变量的引用)

时间:2012-04-08 22:25:27

标签: javascript closures private object-create

我想知道如何通过clojure在javascript中创建私有变量。但是在使用 Object.create 时仍然可以克隆它们。

var point = {};
(function(){
  var x, y;
  x = 0;
  y = 0;
Object.defineProperties(point, {
    "x": {
      set: function (value) {
        x = value;
      },
      get: function() {
        return x;
      }
    },
    "y": {
      set: function (value) {
        y = value;
      },
      get: function () {
        return y;
      }
    }
  });
}());

var p1 = Object.create(point);
p1.x = 100;
console.log(p1.x); // = 100
var p2 = Object.create(point);
p2.x = 200;
console.log(p2.x); //= 200
console.log(p1.x); //= 200

我从http://ejohn.org/blog/ecmascript-5-objects-and-properties/得到了这个技术,但它有这个限制,闭包变量在所有对象上是相同的。我知道javascript上的这种行为是假设的,但我怎样才能创建真正的私有变量?

2 个答案:

答案 0 :(得分:3)

  

我知道javascript上的这种行为是假设但是如何创建真正的私有变量?

你不能,ES5中没有私人。如果需要,可以使用ES6私人名称。

您可以使用ES6 WeakMaps模拟ES6私人名称,这些名称可以在ES5中进行填充。这是一种昂贵且难看的仿真,不值得花费。

答案 1 :(得分:0)

当您需要将私有变量添加到使用Object.create创建的一个对象时,您可以执行以下操作:

var parent = { x: 0 }
var son = Object.create(parent)
son.init_private = function()
{
    var private = 0;
    this.print_and_increment_private = function()       
    {
        print(private++);
    } 
}
son.init_private()
// now we can reach parent.x, son.x, son.print_and_increment_private but not son.private

如果你想要甚至可以避免不必要的公共函数init_private,如下所示:

(function()                                                                                                                                                                                                    
{                                                                                                                                                                                                              
    var private = 0;
    this.print_and_increment = function()
    {
        print(private++);
    }
}
).call(son)

不好的是,您无法通过多次调用追加私有成员。好消息是,我认为这种方法非常直观。

此代码已使用Rhino 1.7发布3 2013 01 27

进行测试
相关问题