关于javascript:函数前的加号是什么?

What is the plus sign before a function?

本问题已经有最佳答案,请猛点这里访问。

这是bootstrap.js中的js代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* ========================================================================
 * Bootstrap: collapse.js v3.1.1
 * http://getbootstrap.com/javascript/#collapse
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */



+function ($) {
  'use strict';

  // COLLAPSE PUBLIC CLASS DEFINITION
  // ================================
   ...
  }

我见过";"在函数定义之前避免混合代码。但是"+"符号在函数之前意味着什么?它是否要将返回值转换为字符串?


它通常与IIFE/SIFE一起使用。当您使用这样的+符号时,它会对后面的表达式进行计算,因此当您将它放入函数中时,它甚至会执行一个匿名函数,就像这样

1
2
3
+function(){
    console.log("Welcome");
}()

产量

1
Welcome

当整个函数都用括号括起来时,这是获得相同行为的另一种方法,如下所示

1
2
3
(function(){
    console.log("Welcome");
}());

注:不只是+,任何一元算术运算符都会给出相同的结果。


它被称为一元加运算符:

The unary plus operator precedes its operand and evaluates to its
operand but attempts to converts it into a number, if it isn't
already. For example, y = +x takes the value of x and assigns that to
y; that is, if x were 3, y would get the value 3 and x would retain
the value 3; but if x were the string"3", y would also get the value
3