greenV
greenV

Reputation: 321

Function that returns value and provides access to inside-defined methods

How to have global object myLib to be, at the same time, library-style function that takes parameters and returns boolean value (true/false) and, let's call it container for other, publicly accessible methods, like this:

window.myLib = (function(w){

    //...
    function on(arg, callback){
    }

    return function(arg1, arg2){
        //returns true or false, based on calculation on arg1, arg2...
    }

})(window)        

myLib('something', 'somethingother')// will return true or false        
myLib.on('somecondition', function(){})// note the on() method-that's what I'm trying to accomplish        

or should I ask, is that possible?

Upvotes: 1

Views: 43

Answers (2)

Ori Drori
Ori Drori

Reputation: 192287

Functions in javascript are objects, so you can actually add methods to them. From mdn:

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

window.myLib = (function(window){
    function myLib(a, b) {
        console.log(a, b);
    }

    myLib.method1 = function (a) {
        console.log(a);
    }

    myLib.method2 = function (a, b) {
        console.log(a + b);
    }

    return myLib;

})(window);

And now you can use both the function, and attached methods:

myLib(1, 2);

myLib.method1(5);

myLib.method2(5, 3);

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

It's possible like this

window.myLib = (function(w){

    //...
    function on(arg, callback){
    }

    function main(arg1, arg2){ // main is an arbitrary name with no significance
        //returns true or false, based on calculation on arg1, arg2...
    }
    main.on = on;
    return main;

})(window)      

Upvotes: 1

Related Questions