JavaScript Revealing Module Pattern全局变量未定义

时间:2015-05-20 19:33:00

标签: javascript html onload revealing-module-pattern

我正在尝试使用Revealing Module Pattern在我的页面上对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未定义。为什么呢?

2 个答案:

答案 0 :(得分:3)

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

请参阅以下代码段以获取解释。

&#13;
&#13;
  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
&#13;
&#13;
&#13;

答案 1 :(得分:0)

正如其他人所提到的,您的代码就像书面一样工作。在您编写它之后,otherFunc返回undefined,因为它没有返回语句来显式返回值。

当您调试此类内容时,最好同时检查您分别调用的对象和功能:

function otherFunc() {
    return "This is otherFunc's return."
}

你也可以尝试添加一个返回到otherFunc:

{{1}}