简体   繁体   English

为什么在这里需要分号?

[英]Why a semicolon is necessary here?

I realise in the following JavaScript code, we need to add a ; 我意识到在以下JavaScript代码中,我们需要添加; just after $('#myButton').click(function() {}) to let $('.lala').myFunction() to be called. $('#myButton').click(function() {}) ,即可调用$('.lala').myFunction()

$('#myButton').click(function() {})

(function ($) {
    $.fn.myFunction = function (opt) {
      alert("inside myFunction")
    }
})(jQuery);

$('.lala').myFunction()

JSBin 联合会

Why ; 为什么; makes a big difference here? 在这里有很大的不同? I thought in most of the cases ; 我想大多数情况下; between statements can be omitted in JavaScript. 在JavaScript中可以省略之间的语句。

Because a function call can return another function. 因为一个函数调用可以返回另一个函数。 Without the semicolon, the parentheses around the IIFE are interpreted as being the argument list to the function that .click() might return, so it's treated as if you'd written: 如果没有分号,则IIFE周围的括号将被解释为.click .click()可能返回的函数的参数列表,因此将其视为已编写:

$('#myButton').click(function() {})(function ($) {
    $.fn.myFunction = function (opt) {
      alert("inside myFunction")
    }
})(jQuery);

Just get out of the habit of depending on automatic semicolon insertion, since the results are sometimes not obvious. 只是摆脱依赖自动分号插入的习惯,因为有时结果并不明显。 If you always put semicolons after your statements, you won't get surprises and don't have to worry about obscure cases like this. 如果您始终在语句后加上分号,则不会感到意外,也不必担心此类晦涩的情况。

The absence of a semicolon here is causing the interpreter to think you are trying to pass the second function as an argument of the firs and then trying to call the result of the first function call as a function. 此处缺少分号使解释器认为您正在尝试将第二个函数作为冷杉的参数传递,然后尝试将第一个函数调用的结果作为一个函数调用。

It's basically doing this: 基本上是这样做的:

$('#myButton').click(function () {
    //...
}(function () {
    //...
})(jQuery);

The second function will fail. 第二个功能将失败。 This is one of the classic examples of why it's great practice to always put semicolons after your statements, as it can create very ambiguous cases. 这是经典的例子之一,这是为什么总是在语句后加上分号是一种很好的做法,因为它会产生非常模糊的情况。 There's really no reason not to. 确实没有理由不这样做。

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

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