问题
In the following example I am using Kyle Simpson's "OLOO (Objects Linking to Other Objects) Pattern" to create a simple example of object serialization.
I need to keep variable _data
private (I am using a closure) and expose its properties only with getter and setters which are create on object instance level (in init
).
Currently I defined function toJson
inside init
so it can access _data
and it works but, I would like to know:
- If would be possible to move
toJson
function outsideinit
(place it at same level offromJson
) so it will accessible via protoype chain but allowing to access_data
variable (I suspect it is not possible because_data
it is in a closure). - Otherwise could you suggest a better alternative(even using ES6) keeping in consideration that
_data
should not be enumerable and not modifiable apart using 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:
I need to keep variable
_data
private (I am using a closure). Would it be possible to movetoJson
function outsideinit
?
No. Private variables cannot be accessed from outside.
来源:https://stackoverflow.com/questions/40395762/oloo-how-to-access-private-variable