Why need to use semicolon before defining a function? [duplicate]

我只是一个虾纸丫 提交于 2019-12-21 04:25:31

问题


I've seen some strange ; at the beginning of a function in some jQuery plugins source code like this:

;(function ($) {.....

Can someone explain why they need to use ; in this case?


回答1:


This semicolon will help you to properly concatenate a new code into a file when the current existed code in this file does not include a ; at the end.

For example:

(function() {

})()  // <--- No semicolon

//  Added semicolon to prevent unexpected laziness result from previous code    
;(function ($) {

})();

Without the semicolon, the second () would have been interpreted as a function call, and will tried to call the return result of the first function




回答2:


This is just to make sure to terminate any previous instruction.

the semi colon before function invocation is a safety net against concatenated scripts and/or other plugins which may not be closed properly.

https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/extend.html



来源:https://stackoverflow.com/questions/16319510/why-need-to-use-semicolon-before-defining-a-function

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