Last active
December 19, 2015 13:49
-
-
Save SleepWalker/5965255 to your computer and use it in GitHub Desktop.
JavaScript object encapsulation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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