Search code examples
javascriptdesign-patternsrevealing-module-pattern

Using the Revealing Module Pattern, why is this object changed?


Given the following code:

var House = function(x, y) {
    var _posX;
    var _posY;

    function init(x,y) {
        _posX = x;
        _posY = y;
    }

    // Auto init
    init(x, y);


    // Public
    return {
        posX: _posX,
        posY: _posY,

        setPosition: function(x, y) {
            _posX = x;
            _posY = y;
        }
    };
};

If I create a new House object:

var house = new House(3,4);

And use the setPosition method to change the position:

house.setPosition(100,50);

I expected that the house position would still be 3,4.. But it however changed (which is actually what I want, but I don't understand how this is possible?) I dont'understand it since Javascript already returned the position which is 3,4 and I would expect it to be like that all the time, even if I change the position using the set method.

console.log(house.posX + ',' + house.posY); // 100,50 (why not 3,4?)

Bonus question: is there a proper way to do the init rather than placing it, ugly in the middle of the code?


Solution

  • This behaviour is due to a closure.

    Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.

    _posx and _posy were defined in a surrounding scope and setPosition remembers it.

    By the way, I think that init should be removed and you should directly assign _posx and _posy in your constructor function.