Search code examples
javascriptecmascript-5

JS closure to return object instance as interface


I have the following code.

function Test() {
this.funct_1 = function() {
    alert('funct_1');
}

this.funct_2 = function() {
    alert('funct_2');
}
return this;}

function getTestObj() {
var testObj;
if (!testObj) {
    testObj = new Test();
}
return function() {
    return testObj;
}}

What I'm trying to accomplish is the following. I want to have a class Test which is not singleton. Then in some other places in my application I need to have a function which could return the same instance per script execution. I figured that I could use closure for that getTestObj.

However, when I try to use it

getTestObj().funct_1();

I'm getting the following error, saying the funct_1() is not found.

Cannot find function funct_1 in object function () {...}.

Clearly, I'm making some kind of mistake here, but I'm not able to find any solution over the net which could help me. Would appreciate any comments.

NOTE: I'm forced to use ECMA5


Solution

  • testObj is wrapped inside a function

    So, either call it

    getTestObj()().funct_1(); //notice two ()()
    

    Save the value of getTestObj() in a variable

    var singleTon = getTestObj();
    var testObj = singleTon();
    testObj.funct_1();
    

    Or, simply return testObj (in case singleTon isn't required)

    function getTestObj() 
    {
       var testObj;
       if (!testObj) {
          testObj = new Test();
       }
       return testObj;
    }
    

    And invoke it as

    getTestObj().funct_1(); //notice single ()