获取构造函数的JavaScript未定义

时间:2013-10-17 09:04:35

标签: javascript namespaces

这是我的代码:

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未定义。

2 个答案:

答案 0 :(得分:5)

试试这个:

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();
});

答案 1 :(得分:1)

Working DEMO

或者您可以使用object literal模式:

var myApp = {};

myApp.jira = {

      getId: function () {
         return ...;
      },

      init: function() {
         var id = this.getId();
      }
    };