2

I am trying to refactor a big JQuery file into smaller ones, but one of the things is I have to be able to call functions inside another JQuery file, but I cant get it to work. So how do I change this code so I can call someFunction inside File1.js from from File2.js?

//File1.js
(function (s_diary, $, undefined) {

function someFunction()
{
    alert("Yay");
}

} (window.s_diary= window.s_diary|| {}, jQuery));

//File2.js
(function (s_one, $, undefined) {

function someFunction()
{
    s_diary.someFunction();
}

} (window.s_one= window.s_one|| {}, jQuery));
2
  • You can't; that's the point of such private variables. Commented Aug 25, 2011 at 8:12
  • Why is pastebin.com/mqSBrJ3j then able to call the init from outside? Commented Aug 25, 2011 at 8:18

2 Answers 2

3

Look at it more closely, formatting, comments, and changes to show point:

(function (s_diary, $, undefined) {
  // the someFunction function is private to this function
  // it has the same scope as a function parameter or local var
  function someFunction() {
    alert("Yay");
  }
  // but since all functions are just objects...
  // someFunction is now *exposed* as window.s_diary.someFunction
  // see below for why window.s_diary is modified
  s_diary.someFunction = someFunction
}(window.s_diary = window.s_diary || {}, jQuery));

Note that last (...) bit invokes the function-object previously defined and passes in the object (creating it if needed) known by the name window.s_diary. Then inside the function the "window.s_diary" object is mutated. Remember that window is the global namespace and is thus available to all scrips within a single page context. (Just make sure they are run in the correct order.)

Happy coding.

Sign up to request clarification or add additional context in comments.

Comments

2

Perhaps you can do it like this, it is called "revealed module pattern" if I recall correctly:

var file1 = (function (s_diary, $, undefined) {

function someFunction()
{
    alert("Yay");
};
return{
    someFunction: someFunction
};
} ());

var file2 = (function (s_one, $, undefined) {

function someFunction()
{
    file1.someFunction();
}

} (window.s_one= window.s_one|| {}, jQuery));

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.