Search code examples
javascriptfunctioncalldefault

javascript: call a default function?


I need to make some js functionality like that:

let text =function()
{
    this.main = ...;
    this.toArr = ...;
};

let t = new text();

console.log( t() ); // call a function 'main' in text;
t().toArr(); // call a function 'toArr' in text;

Solution

  • Try this:

    let text = function (myarg) {
        // Usage: var t = new text(<arg>);
        this.uniqueProperty = "test";
        var main = () => {
            // main code
            return {
                toArr: () => {
                    return [myarg, this.uniqueProperty];
                }
            };
        };
        return main;
    }
    
    var t = new text("hey world");
    
    console.log(t());
    console.log(t().toArr());

    Calls are the same as in your question

    Note: your main function returns object now.


    How does this work?

    You call new text("arg"), but constructor returns main function instead of this. Main function returns object with toArr function, and can be accessed through new text("arg")().toArr code. Why I put both functions into () => {}?. The answer is simple - that's how to access text instance properties. So we can access unique text properties. Else, this will be main function reference.