Javascript私有变量+;Object.create(引用闭包变量)
我想知道如何通过clojure在javascript中生成私有变量。但在使用对象时仍将其克隆。创建Javascript私有变量+;Object.create(引用闭包变量),javascript,closures,private,object-create,Javascript,Closures,Private,Object Create,我想知道如何通过clojure在javascript中生成私有变量。但在使用对象时仍将其克隆。创建 var point = {}; (function(){ var x, y; x = 0; y = 0; Object.defineProperties(point, { "x": { set: function (value) { x = value; }, get: function() { return
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
我从中得到了这种技术,但它有一个局限性,即闭包变量在所有对象上都是相同的。我知道javascript上的这种行为是假定的,但是我如何才能创建真正的私有变量呢
我知道javascript上的这种行为是假定的,但是我如何才能创建真正的私有变量呢
你不能,在ES5中没有隐私。如果需要,可以使用ES6私有名称
您可以使用ES6弱映射模拟ES6私有名称,这些弱映射可以在ES5中填充。这是一个昂贵且丑陋的模拟,不值得花费。当您需要仅向一个使用object创建的对象添加私有变量时。create您可以这样做: 如果需要,您甚至可以避免不必要的公共函数init_private,如下所示: 糟糕的是,您不能在几个调用中附加私有成员。好的是,在我看来,这种方法非常直观
这段代码是用Rhino 1.7 release 3 2013 01 27测试的这段代码看起来是自动生成的,它是由clojure代码生成的吗?不是,为什么你认为它看起来是自动生成的?作为一个没有私有变量的替代方案,我认为,作为一个没有私有变量的替代方案,它可能是
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
(function()
{
var private = 0;
this.print_and_increment = function()
{
print(private++);
}
}
).call(son)