Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active April 10, 2016 07:33
Show Gist options
  • Select an option

  • Save Williammer/e259dac12d8178862e4c to your computer and use it in GitHub Desktop.

Select an option

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.
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