Setting Methods and Properties

by Lucas Krause

JavaScript

(function)(win, myMethod, someOtherMethod){ //2.
    var args=Array.prototype.slice.call(arguments, 1), //3.
        myLib=function(){
            console.log("Do some super cool stuff with the arguments:", arguments);
        };
    
    myMethod=function(){
        console.log("I'm a method of the MyLib Object");
    };
    
    someOtherMethod=function(){
        console.log("I get never called because people are too lazy to type out my name!");
    };
    
    /**
     * 4.
     *
     * Here the magic happens.
     * This is much cooler than doing something like
     *
     *     myLib.myMethod=myMethod;
     *     myLib.someOtherMethod=someOtherMethod;
     *
     * for every method and property. That would be redundant.
     * Or even worse since `eval()` is evil :D
     *
     *     var methods=["myMethod", "someOtherMethod"];
     *     for(var i=0; i<methods.length; i++){
     *         myLib[methods[i]]=eval(methods[i]);
     *     }
     */
    for(var i=0; i<args.length; i++){
        myLib[args[i]]=arguments[i+(arguments.length-args.length)];
    }
    
    win.MyLib=myLib;
})(window, "myMethod", "someOtherMethod"); //1.

/**
 * Sure, you could also use a `with` statement.
 * But I think at the latest when you read the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with), that using a `with` statement wouldn't be an option to you any more.
 */