javascript 中的函数用括号括起来

functions in javascript wrapped in parenthesis

我是 javascript 的新手,我可能先深入了解了。我在阅读 js 中的设计模式时遇到了以下定义。我不明白这里使用的语法,为什么"log"函数定义在"()",

var log = (function() {
    var log = "";
    return {
        add: function(msg) { log += msg + "\n"; },
        show: function() { alert(log); log = ""; }
    }
})();

请指出正确的方向。

如果没有括号,赋值的右侧是一个函数表达式,并且 log 被赋值一个对该(匿名)函数表达式的引用,允许稍后调用 log()

如果包含括号,包装函数将变成一个自调用函数表达式(并立即执行),因此无论此函数调用什么 log 都会赋值 returns.

正如其他人所说,您的代码显示了所谓的 模块模式 的示例。阅读更多相关信息 here

I don't understand the syntax used here, why is the "log" function definition in "()"

它基本上是自执行匿名函数。有几种编写此类函数的方法。

(function() {
  alert('hi there');
})();

! function() {
  alert('hello');
}();

+ function() {
  alert('plus');
}();

- function() {
  alert('minus');
}();

现在这样的函数也可以return取值:

var msg = (function() {
  return 'hello';
})();

alert(msg);

var calc = (function() {
  return {
    add: function(a, b) {
      return a + b;
    },
    sub: function(a, b) {
      return a - b;
    }
  };
})();

alert(calc.add(4, 5));