Search code examples
javascriptclosuresprivateobject-create

Javascript private variables + Object.create (reference to closure variables)


I was wondering how I could make private variables in javascript through clojure. But still have them cloned when using 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

I got this technique from http://ejohn.org/blog/ecmascript-5-objects-and-properties/ but it got this limitation that the closure variables is the same on all Objects. I know this behaviour on javascript is supposed but how can I create true private variables?


Solution

  • I know this behaviour on javascript is supposed but how can I create true private variables?

    You can't, there is no private in ES5. You can use ES6 private names if you want.

    You can emulate ES6 private names with ES6 WeakMaps which can be shimmed in ES5. This is an expensive and ugly emulation, that's not worth the cost.