0

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?

user3125591
  • 113
  • 5
  • 13
  • how do you determine that the position has changed? It actually changes something, but nothing you can ever inspect with the code you provided. – Thomas May 29 '16 at 17:16
  • you can shorten the code, by replacing everything before the return with `var House = function(_posX, _posY) { return ...` – Thomas May 29 '16 at 17:18
  • @Thomas Thanks for the reply. Sorry, not sure whether I understand your comment, I updated my answer. Simply by logging the position after changing the code. Regarding your second comment, that would make everything public right? – user3125591 May 29 '16 at 17:54
  • for me, the code works as expected, and `console.log(house.posX + ',' + house.posY)` shows `3,4`. Can you provide some testarea for us, where you can reproduce this error? – Thomas May 29 '16 at 21:01

1 Answers1

0

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.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35