我想知道如何通过clojure在javascript中创建私有变量。但是在使用Object.create时仍然会克隆它们。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上的行为是假设,但我怎样才能创建真正的私有变量?
这个代码看起来自动生成测试,是由Clojure的代码产生的呢? – Raynos 2012-04-08 22:38:43
不是这不是你为什么认为它看起来自动生成? – automaticoo 2012-04-08 22:45:57
作为没有私有变量的替代方案可以是http://jsfiddle.net/heera/G9E9m/ – 2012-04-08 23:34:29