Why does rejecting a semicolon interrupt this code?

Or in another way, why the semicolon insert is completed, and the code below is broken.

function Foo() { }

Foo.prototype.bar = function () {
    console.log("bar");
} // <------------ missing semicolon

(function () {
    Foo.prototype.la = function () {
        console.log("la");
    };
})();

Why is JavaScript parsing mechanism trying to combine Foo.prototype.bar = function () {with what's in my closure? Is there anything that I could contribute to this closure that would make this reasonable?

I do not advocate leaving a semicolon, expecting a semicolon to save you; I'm just wondering why (the more useful version) the above code broke when I accidentally left one.

+4
source share
2 answers

Think of it this way:

Foo.prototype.bar = function () { // <-- 1. function
    console.log("bar");
}(function () {    // <-- 2. call the 1. function, passing a function argument
    Foo.prototype.la = function () {
        console.log("la");
    };
})();  // <-- 3. tries to invoke the return value of the 1. function, 
       //            but "undefined" was returned.

I do not like to use ()for IIFE. I prefer other operators.

Foo.prototype.bar = function () {
    console.log("bar");
}

void function () {
    Foo.prototype.la = function () {
        console.log("la");
    };
}();

, , , .

Foo.prototype.bar = function () { // <-- 1. function

    console.log("bar");
    return function() { alert('INVOKED'); }; // 2. return a function

}(function () {    // <-- 3. call the 1. function, passing a function argument
    Foo.prototype.la = function () {
        console.log("la");
    };
})();  // <-- 4. tries to invoke the return value of the 1. function,
       //         which will now call the returned function with the "alert()"

, @Lasse Reichstein, - , .

+3

( , ( ).

+4

All Articles