devshorts
devshorts

Reputation: 8872

Why are functions on the object being executed from a self executing function?

I have an application that in debug mode is written in many separate javascript files, but are loaded synchronously as part of the head block of a page. In release, I merge all these files together and minifiy them. Today I kept finding an error in the minified version, so I loaded up a single merged file to debug the issue and found that one library was self executing a function and it was causing other functions defined on window to be executed.

I've repo'd the behavior here with a generic object, doesn't matter if its window or not:

<head>
    <script>
        var a = {}

        a.X = function x(){
            console.log("shouldn't be executed");
        }

        (function(a){
            console.log("self execution");
        }(a));
     </script>
</head>

In this example, I get the output of

self execution 
shouldn't be executed 

If I change the call to be

<head>
    <script>
        var a = {}

        function x(){
            console.log("shouldn't be executed");
        }

        a.X = x;

        (function(a){
            console.log("self execution");
        }(a));
     </script>
</head>

Then I just get

self execution

Which is what I expected. In the first example, why is X getting called when a is passed to the self executing function?

Upvotes: 13

Views: 235

Answers (3)

Quentin
Quentin

Reputation: 943936

You are missing the ; after you assign the function to a.X.

Semi-colon insertion is not triggered.

The ( and ) around the anonymous function are used to call the previous function, and its return value is assigned to X.

i.e. what you have is equivalent to:

var a = {};

a.X = (function x(){
    console.log("shouldn't be executed");
}(
    (function(a){
        console.log("self execution");
    }(a))
));

Incidentally, this issue is a good advert for JS Lint, which would have picked it up.

Upvotes: 22

Naveen Kumar Alone
Naveen Kumar Alone

Reputation: 7678

You have missed a semicolon ; after your a.X = function x() { ...} ;

i.e.

a.X = function x(){
   console.log("shouldn't be executed");
};

Upvotes: 1

jcubic
jcubic

Reputation: 66590

It have something to do with semicolon injection because when I put semicolon it work as expected:

    var a = {}

    a.X = function x(){
        console.log("shouldn't be executed");
    }; // added semicolon

    (function(a){
        console.log("self execution");
    }(a));

Upvotes: 3

Related Questions