Self executing function passing object after condition

情到浓时终转凉″ 提交于 2019-12-31 02:58:21

问题


I have come across a self executing function that executes on a condition that the declared containing var exists, and if it doesn't exist it is passed an object.

Example:

var myFunc = (function(myFunc){}(myFunc || {}));

How come there is an "or" condition operator that passes an object ?


回答1:


var myFunc = (function(myFunc){}(myFunc||{}));

This doesn't make any sense because the myFunc Argument will always be {} - I'm confused by that.

Ill explain one that does

First Example

var cool = {
   person: 'john'
};

(function( Argument ){
  console.log( Argument ); // Result Object {person: "john"} 
}( cool || {} ));

In this example cool is defined and is a object so it wont go past the ||


Next example

var cool;
(function( Argument ){
  console.log( Argument ); // Result Object {}
}( cool || {} ));

In this example cool is defined But the defualt value for a variable is undefined so in this case it is undefined so Argument is a Object instead




回答2:


The code you provided is an example of the module pattern. In particular it's an example of loose augmentation of the module pattern.

The module pattern is basically just an immediately invoked function expression (IIFE) which returns an object. For example:

// file 1

var MODULE = (function () {
    var my = {}, privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;

    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

Augmentation allows you to split a module into parts. Each part can reside in it's own file. For example we can augment the above module as follows:

// file 2

var MODULE = (function (my) {
    my.anotherMethod = function () {
        // added method...
    };

    return my;
}(MODULE));

However in this pattern of augmentation file 1 must be loaded before file 2 or else you'll get an error. Loose augmentation allows you to load files in any order.

var MODULE = (function (my) {
    // add capabilities...

    return my;
}(MODULE || {}));

In the above example the module MODULE may be split over multiple files which can be loaded in any order. The expression MODULE || {} evaluates to MODULE if it exists. Otherwise it evaluates to {}.

Hence for the first file that's loaded the expression will evaluate to {} because MODULE would initially be undefined. In subsequent files the expression would evaluate to MODULE.



来源:https://stackoverflow.com/questions/17630377/self-executing-function-passing-object-after-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!