0

我正在尝试使用显示模块模式来确定我页面上的 JavaScript 范围,这样我就不会污染全局命名空间。

<script type="text/javascript">
  var myModule = (function(){
    function windowLoad() {
       // window onLoad things
       return;
    }

    function otherFunc(){ 
      // otherFunc things 
    }

    window.onload = windowLoad;

    return { otherFunc: otherFunc };
  })();

  myModule.otherFunc(); // myModule is undefined here
</script>

出于某种原因,如上面的评论所示,myModule当我去使用它时是未定义的。为什么?

4

2 回答 2

3

myModule不是未定义的。它是您从立即调用的函数中返回的对象;未定义的是调用的结果,myModule.otherFunc因为该函数不返回任何内容。

有关说明,请参见以下代码段。

  var myModule = (function() {
    function windowLoad() {
      // window onLoad things
      return;
    }

    function otherFunc() {
      return 1;
    }

    window.onload = windowLoad;

    return {
      otherFunc: otherFunc
    };
  })();

  console.log(myModule); // object {otherFunc: function otherFunc(){...}}
  console.log(myModule.otherFunc()); // 1

于 2015-05-20T19:45:08.463 回答
0

正如其他人所提到的,您的代码按书面方式工作。如您所写, otherFunc 返回 undefined 因为它没有用于显式返回值的 return 语句。

当你调试这样的东西时,最好分别检查你正在调用的对象和函数:

console.log(myModule); // should print [Object object]
console.log(myModule.otherFunc); // should print a function definition

您也可以尝试向 otherFunc 添加返回:

function otherFunc() {
    return "This is otherFunc's return."
}
于 2015-05-20T19:55:57.407 回答