javascript - 函数前的加号是什么?

标签 javascript twitter-bootstrap

<分区>

这是来自 bootstrap.js 的 JS 代码

/* ========================================================================
 * 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 一起使用。当你像那样使用 + 符号时,它会计算后面的表达式,所以当你把它放在一个函数中时,它甚至会执行一个匿名函数,就像这样

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

输出

Welcome

当整个函数用括号括起来时,这是获得相同行为的另一种方法,就像这样

(function(){
    console.log("Welcome");
}());

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

关于javascript - 函数前的加号是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317743/

相关文章:

javascript - 正则表达式:如何重复模式匹配?

javascript - 设置状态(...): This usually means you called set state() on an unmounted component

javascript - Meteor + Bootstrap 3 Glyphicons 不工作

javascript - 在 bootstrap navbar-collapse 中居中站点地图菜单。随着屏幕尺寸的变化删除空白

html - 在另一个模态上 Bootstrap 模态

javascript - 日期范围选择器如何在输入日期时触发事件

php - 用 PHP 打印成 Javascript

javascript - 如何从数组中删除所有奇数索引(例如 : a[1], a[3]..)值

javascript - Angular 双向数据绑定(bind)问候语

javascript - Bootstrap 图像模态