为什么 public 方法不在 IIFE 中打印?

How Come public method is not printing in a IIFE?

由于 return 语句,不应该在控制台中打印 hello 吗?由于末尾的 () ,代码会立即被调用,为什么不打印呢?

var Module = (function () {

var privateMethod = function () {
// private
 };

  var someMethod = function () {
    // public
    console.log('hello');
  };

  var anotherMethod = function () {
    // public
  };

  return {
    someMethod: someMethod,
    anotherMethod: anotherMethod
  };

})();
return {
   someMethod: someMethod,  // just a function reference
   anotherMethod: anotherMethod // again a function reference
};

所以,您不是调用该函数。 您只是返回附加到对象的 属性 的函数引用。 尝试在此处使用逗号运算符,它计算最右边的语句,同时执行 someMethod()函数。

return {
 someMethod: someMethod(), someMethod, // first getting called and someMethod ref is passed to the property
 anotherMethod: anotherMethod
};

因为 var 关键字位于 Module 的最前面。

如果您在控制台中执行以下操作:

var a = 5 // a 设置为 5 但未定义显示在控制台中。

如果您要删除 var 关键字:

a = 5 // a 再次设置为 5 但 5 显示在控制台中。

但在您的实际代码中,您可能希望使用 var 关键字。

所以简单地说,这只是控制台的输出方式,我不知道为什么。

启发更多,

function 本身是 Function 的对象(参见 https://msdn.microsoft.com/en-us/library/ie/x844tc74%28v=vs.94%29.aspx

所以基本上你添加了一个对函数类型对象的引用,它不是 IIFE。