3

this is my code:

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

when the page is loaded it says jira is undefined.

2
  • add return init at the end of the function Commented Oct 17, 2013 at 9:07
  • @bhb - return init; will not fix it entirely. It would require different syntax later: myApp.jira(). Or, as in my answer: return { init: init } and rest same as in original code. Commented Oct 17, 2013 at 9:19

2 Answers 2

5

Try this:

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();
});
Sign up to request clarification or add additional context in comments.

Comments

1

Working DEMO

Or you can use object literal pattern instead:

var myApp = {};

myApp.jira = {

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.