Last active
April 10, 2016 07:33
-
-
Save Williammer/e259dac12d8178862e4c to your computer and use it in GitHub Desktop.
[email protected] - the implementation of private variables with closure; be cautious when passing reference type values, they allow modification of themselves from the variable it passed.
This file contains hidden or 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
| function Gadget() { // private member | |
| //var specs = { | |
| var screen_width = 320, | |
| screen_height = 480, | |
| color = "white" | |
| // }; | |
| // public function | |
| this.getSpecs = function () { | |
| //return new object to protect variable privacy | |
| return { | |
| "screen_width": screen_width, | |
| "screen_height": screen_height, | |
| "color": color | |
| }; | |
| }; | |
| } | |
| var g = new Gadget(); | |
| var test = g.getSpecs(); | |
| test.screen_width = 1280; | |
| test.screen_height = 640; | |
| test.color = "blue"; | |
| //will not be changed. | |
| console.log(g.getSpecs()); | |
| //Another way is to copy the object to be returned. | |
| //to be continued... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment