Williammer
6/4/2014 - 9:54 AM

jsPatterns.privateScope@closure.js - the implementation of private variables with closure; be cautious when passing reference type values, t

jsPatterns.privateScope@closure.js - 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...