weixin

javascript function前面的加号是什么意思

日期: March 19, 2019 作者:网站维护

JS 里总有一些看起来很怪异的东西。比如在bootstrap里的js文件里,每一个js文件的function前面有一个+号。

需要先知道JS里 function declaration 和 function expression的区别。

比如:function foo(){},这就是function declaration(函数声明)

var a = function(){},这就是一个function expression(函数表达式)

在function前面加个+号,为了让解释器认为这个部分是一个函数表达式而不是声明。默认情况解释器认为function开头是的函数声明。虽然这两者使用上也没什么太大区别。只是在执行之前,js会先找到函数的参数,函数的声明和变量声明,放入执行环境。找到function开头的便认为是函数声明。而函数表达式是在执行阶段才会处理。

那么为什么要需要这个加号。加上加号,+function(){}() 这个表达式就成了自执行函数,和(function(){})()一样了。

参考:javascript function前面的加号

It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:

+function() { console.log("Foo!"); }();

Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.

+ is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):

(function() { console.log("Foo!"); })(); // or (function() { console.log("Foo!"); }());

It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:

+function() { console.log("Foo!"); }();

Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.

+ is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):

(function() { console.log("Foo!"); })(); // or (function() { console.log("Foo!"); }());

广告内容为平台自动生成