简体   繁体   English

为什么不使用分号会破坏此代码?

[英]Why does leaving off a semicolon break this code?

Or put another way, why does semicolon insertion fail, leaving the code below broken. 换句话说,为什么分号插入失败,以下代码被破坏。

function Foo() { }

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

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

Why is the JavaScript parsing engine trying to combine Foo.prototype.bar = function () { with what's in my closure? 为什么JavaScript解析引擎试图将Foo.prototype.bar = function () {与我的闭包中的内容结合起来? Is there anything I could put in that closure that would make this sensible? 有什么我可以放在那个关闭会使这个明智吗?

I'm not advocating leaving off semicolons with the expectation that semicolon insertion will save you; 我不是主张不用分号,期望分号插入可以挽救你; I'm just wondering why (a more useful version of) the above code broke when I accidentally left one off. 我只是想知道为什么(一个更有用的版本)上面的代码在我意外地离开一个时打破了。

因为它看到了(在下面的行上并且认为你想要调用上面的内容(使用下面的函数作为参数)。

Think of it like this... 想想这样......

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 don't like using () for IIFE. 我不喜欢IIFE使用() I prefer other operators. 我更喜欢其他运营商。

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

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

If we go back to the original, and have the first function return a function, you'll see that one invoked. 如果我们回到原来的,并让第一个函数返回一个函数,你会看到一个函数被调用。

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()"

Updated to use a unary operator as suggested by @Lasse Reichstein , as a binary operator will still evaluate its left and right operands, and return the result, which will be used for the assignment. 更新为使用@Lasse Reichstein建议的一元运算符,因为二元运算符仍将评估其左右操作数,并返回将用于赋值的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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