Search code examples
javascriptmoduleiife

How can i make this object pattern work?


This pattern really floats my boat but how can i make it act as a base class without using 'new', 'this' nor 'Object.create()'? Is it possible?

var myObj = (function () {

    var x = 0;
    var privFunc = function() { console.log(x); };

    // interface
    return { 
        init    : function (arg) { x=arg; },
        getVal  : privFunc
    };

}());

var abc = myObj;
abc.init(123);
abc.getVal(); //123

var xyz = myObj;
xyz.init(456);
xyz.getVal(); //456

abc.getVal(); //456? want it to return 123

Solution

  • You are creating a single object, and then you just copy the reference to it. If you want separate objects you need to call the function once for each object:

    function myObj() {
    
        var x = 0;
        var privFunc = function() { console.log(x); };
    
        // interface
        return { 
            init    : function (arg) { x=arg; },
            getVal  : privFunc
        };
    
    }
    
    var abc = myObj();
    abc.init(123);
    abc.getVal(); //123
    
    var xyz = myObj();
    xyz.init(456);
    xyz.getVal(); //456
    
    abc.getVal(); //123