我想知道如何通過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