dimanche 29 mai 2016

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.

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

Aucun commentaire:

Enregistrer un commentaire