简体   繁体   中英

Module pattern augmentation

From what I know, this is how you implement loose augmentation to modules:

// file1.js:
var mod = (function(){

    return { foo: 1 }

})();

// file2.js:
var mod = (function(mod){

    console.log(mod); // Object { foo: 1 } 

})(mod || {});

This obviously works, but what I would like a couple of things straighten out:

  1. Is it safe to say that declaring a variable with the same name in javascript will never cause an issue (even in strict mode)?
  2. Why is the mod argument in the second IIFE not overwritten by the second var mod ? Are self executing functions executed before variables are declared?

http://jsfiddle.net/aVV9S/

Is it safe to say that declaring a variable with the same name in javascript will never cause an issue (even in strict mode)?

It depends where you declare that variable. If it is in the global scope, there is a possibility that your variable can be overwritten somewhere else if a variable of that same name is also defined in the global scope.

Why is the mod argument in the second IIFE not overwritten by the second var mod? Are self executing functions executed before variables are declared?

Order of evaluation is such that the function arguments are evaluated first, and then the function itself is evaluated and invoked. It is only after that, that the return value is assigned to the outer mod . Your second example also appears to be mistyped; it should probably be:

var mod = (function(mod){

    console.log(mod); // Object { foo: 1 } 

})(mod || {});

The mod inside the function is local to the scope of that function only. However, realize that once you have invoked this function, mod is no-longer { foo: 1} , but undefined since you are not returning anything from the IIFE.

Regarding your comment, you can actually see the order of execution happening in the following snippet:

var foo = {
    test: function() {
        console.log("hello");
        return 5;
    }
};

var bar = (function(val) {
    console.log("there")
    console.log("bar is", bar);
    return 5;
})(foo.test());
console.log("bar is", bar);

The console will show:

hello
there
bar is undefined
bar is 5

Which shows that the arguments to the IIFE are evaluated first, then the IIFE itself is evaluated and invoked, and finally the value 5 is assigned to bar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM