0

Really trying to nail down closures / OOP concepts in Javascript. Any help is appreciated. Output is via Chrome console.

Both functions build and return an object. The methods in objMaker() use 'this' whereas the methods in staticMaker() uses the closed upon 'obj' object. Curiously, there is no difference in outcome.

Especially, I would think that directly assigning a value to a property of an object returned by staticMaker() would not be reflected by the .showXY() method, since that method refers to a closure and not to the returned object.

function objMaker(x, y) {
    var obj = {};

    obj.x = x;
    obj.y = y;

    obj.showXY = function() {
        console.log("x: " + this.x + " y: " + this.y);
    }

    obj.changeXY = function(x, y) {
        this.x = x;
        this.y = y;
    }

    return obj;
}

function staticMaker(x, y) {

    var obj = {};

    obj.x = x;
    obj.y = y;

    obj.showXY = function() {
        console.log("x: " + obj.x + " y: " + obj.y);
    }

    obj.changeXY = function(x, y) {
        obj.x = x;
        obj.y = y;
    }

    return obj;
}

objMaker() test, using this:

var objMade = objMaker(100, 200);       
console.log(objMade);                   // Object {x: 100, y: 200}
objMade.showXY();                       // x: 100 y: 200
objMade.changeXY(11, 21);   
objMade.showXY();                       // x: 11 y: 21
objMade.x = "blah"; 
objMade.showXY();                       // x: blah y: 21
console.log(objMade);                   // Object {x: "blah", y: 21}

objMaker() test, using obj:

var staticMade = staticMaker(100, 200);         
console.log(staticMade);                // Object {x: 100, y: 200}
staticMade.showXY();                    // x: 100 y: 200
staticMade.changeXY(11, 21);
staticMade.showXY();                    // x: 11 y: 21
staticMade.x = "blah";
staticMade.showXY();                    // x: blah y: 21, expected x: 11 y: 21
console.log(staticMade);                // Object {x: "blah", y: 21}

thanks again

bozzmob
  • 12,364
  • 16
  • 50
  • 73
StayCool
  • 520
  • 6
  • 17
  • 1
    Btw, these functions are called "(object) *factories*", not "object generators" – Bergi Jan 26 '16 at 19:20
  • 1
    "*I would think that directly assigning a value to a property of an object returned by `staticMaker()` would not be reflected by the `.showXY()` method*" - no, the closure refers to the object, not to property values. Changing the object properties will still be reflected. You'd need to close over variables `x` and `y`. – Bergi Jan 26 '16 at 19:23

0 Answers0