在IIFE之前分号的目的是什么? [英] What is the purpose of a semicolon before an IIFE?

查看:207
本文介绍了在IIFE之前分号的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 has.js 的代码并且对这里的初始分号感到困惑:

I was checking out the code of has.js and was puzzled by the initial semicolon here:

;(function(g){
  // code
}()(this);

据我所知,它绝对没有。它确实没有。不要将函数放在表达式位置为() do:(function() {}())!function(){}()。它似乎只是一个空行的行符号。

As far as I know, it does absolutely nothing. It does not put the function in expression position as () or ! do: (function(){}()) or !function(){}(). It seems to be merely a line ender for an empty line.

这个分号的目的是什么?强迫症想要在IIFE的开始和结束之间保持对称?:)

What is the purpose of this semicolon? An OCD desire for symmetry between the beginning and end of the IIFE? :)

推荐答案

这是为了防止任何以前的代码执行你的代码作为函数的参数。

It's there to prevent any previous code from executing your code as the arguments to a function.

ie

mybrokenfunction = function(){

} //no semicolon here
(function(g){


})(this);

将以您的匿名函数作为参数执行mybrokenfunction:

will execute mybrokenfunction with your anonymous function as its argument:

mybrokenfunction = function(){}(function(g){})(this);

如果您可以保证在您之前没有未终止(没有分号)功能,那么您可以省略起始分号,但你不能,所以把额外的分号放进去更安全。

If you could guarantee that there won't be an unterminated (no semicolon) function before yours, you could omit the starting semicolon, but you can't, so it's just safer to put that extra semicolon in.

这篇关于在IIFE之前分号的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆