Question

As far as I know, a lot of javascript code still use IIFE as a pattern of their namespace, and I believe javascript developers are accustomed to there are usually something afters, don't expect you would see everything if you read the code just from the beginning; sometimes empty parenthesis, sometimes more arguments.

I read into part of require.js, and saw the additional arguments adjustment in its define implementation:

define=function (name, deps, callback) {
    var node, context;

    //Allow for anonymous modules
    if (typeof name!=='string') {
        //Adjust args appropriately
        callback=deps;
        deps=name;
        name=null;
    }

    //This module may not have dependencies
    if (!isArray(deps)) {
        callback=deps;
        deps=null;
    }

    // .. 

I'd like to understand things better of why it is defined in this way, and should I follow this fashion when I'm going to define my own APIs?

The spec: AMD

Was it helpful?

Solution

Functions that accept arguments in a random or very optional order just give you some syntactic sugar. It's not necessarily something you should aim for but it's nice if it works out.

I can give an example where the arguments are not nice:

JSON.stringify(data_obj, undefined, "\t");

You have to pass undefined as the replacer function (because I don't have a replacer function, it's optional). Of course it would be trivial to add something like the code you posted that checks the type of the 2nd and 3rd argument to reduce it to:

JSON.stringify(data_obj, "\t");

In Java (not JavaScript) you have polymorphic functions like:

public function get(String string, List list) {}

public function get(List list) {}

Depending on how you call get it will call either of those implementations. When you implement these you might see something like:

public function get(String string, List list) {
     /* actual implementation */
}

public function get(List list) {
    this->get("", list); // call get with default 1st argument
}

So there isn't really that much substance to it, just syntactic sugar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top