How to access a private variable

In the following example, I use Kyle Simpson's "OLOO (Object Linking to Other Objects) Pattern" to create a simple example of serializing an object.

I need to save the _data private variable (I use closure) and set its properties only using getter and seters, which are created at the instance level of the object (in init ).

I have currently defined a toJson function inside init so that it can access _data and it works, but I would like to know:

  • If you could move the toJson function outside of init (put it on the same level fromJson ) so that it is accessible through the protoype chain, but allows access to the _data variable (I suspect that this is impossible because it is _data in a closure).
  • Otherwise, could you suggest a better alternative (even using ES6), considering that _data cannot be enumerated and cannot be modified using a getter and setter?

  // example of serialization and deserialization of an object (function (window) { var dataApi = '{"id":0,"top":10,"left":20,"width":100,"height":150}'; var state = JSON.parse(dataApi); var base = { init: function (data) { var _data = data; // private // defined on object itself not on its protoype Object.defineProperty(this, 'id', { get: function () { return _data.id; }, set: function (value) { _data.id = value; } }); Object.defineProperty(this, 'top', { get: function () { return _data.top; }, set: function (value) { _data.top = value; } }); Object.defineProperty(this, 'left', { get: function () { return _data.left; }, set: function (value) { _data.left = value; } }); Object.defineProperty(this, 'width', { get: function () { return _data.width; }, set: function (value) { _data.width = value; } }); Object.defineProperty(this, 'height', { get: function () { return _data.height; }, set: function (value) { _data.height = value; } }); this.toJson = function () { // move this function to prototype return JSON.stringify(_data); } }, // defined on protoype fromJson: function (json) { var data = JSON.parse(json), obj = Object.create(this); obj.init(data); return obj; } }; // create object with linked prototype using deserialization var wdgA = base.fromJson(dataApi); // serialize object var str = wdgA.toJson(); console.log(str); // create object with data injection var wdgB = Object.create(base); wdgB.init(state); var id = wdgB.id; console.log(id); })(window); 
+1
javascript ecmascript-6 ecmascript-5
Nov 03 '16 at 7:14
source share
1 answer

I need to save the _data private variable (I use closure). Is it possible to move the toJson function outside init ?

No. Private variables are not accessible externally.

+2
Nov 03 '16 at 9:18
source share



All Articles