获取构造函数的JavaScript未定义

这是我的代码:

window.myApp= window.myApp|| {};

myApp.jira = (function () {

  var getId = function () {
     return ...;
  }

  var init = function() {
     var id = myApp.jira.getId();
  }

})();

$(document).ready(function () {
    myApp.jira.init();  // here jira is null and getting undefined
});

当页面加载时,它说jira是未定义的.

最佳答案
试试这个:

window.myApp= window.myApp|| {};

// Function here is being immediately invoked. No "return" statement
// in your code is equivalent to "return undefined;".
myApp.jira = (function () {

  var getId = function () {
     return ...;
  }

  var init = function() {
     var id = myApp.jira.getId();
     // Bonus note: you can simplify this:
     // var id = getId();
  }

  // If we return an object with functions we want
  // to expose (to be public), it'll work,
  return {
    init: init,
    getId: getId
  };

})();  // <-- here you'll invoking this function, so you need return.

$(document).ready(function () {
    // Without 'return' above, myApp.jira evaluated to undefined.
    myApp.jira.init();
});

转载注明原文:获取构造函数的JavaScript未定义 - 代码日志