3

这是我的代码:

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

4

2 回答 2

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();
});
于 2013-10-17T09:07:55.087 回答
1

工作演示

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

var myApp = {};

myApp.jira = {

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

      init: function() {
         var id = this.getId();
      }
    };
于 2013-10-17T09:14:44.750 回答