Skip to content

Instantly share code, notes, and snippets.

@SleepWalker
Last active December 19, 2015 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SleepWalker/5965255 to your computer and use it in GitHub Desktop.
Save SleepWalker/5965255 to your computer and use it in GitHub Desktop.
JavaScript object encapsulation
var myClass = (function () {
var properties = {
foo: 'bar'
};
var obj = function () {};
obj.prototype = {
get: function (key) {
return this['get' + cfirst(key)]();
},
set: function (key, value) {
// магия над запросом
this['get' + cfirst(key)](value);
},
getFoo: function () {
return properties.foo + ' modified with getter';
},
setFoo: function (value) {
alert('The foo value going to be changed');
properties.foo = value;
}
};
function cfirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return obj;
})();
// TEST
var myObj = new myClass();
alert(myObj.get('foo'));
alert(myObj.getFoo());
myObj.foo = 'Hacked';
alert(myObj.foo);
alert(myObj.get('foo'));
myObj.setFoo('Magic');
alert(myObj.foo);
alert(myObj.get('foo'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment