How do access a JQuery function inside a scope in another Jquery file?
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 s开发者_StackOverflowo 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));
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.
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));
精彩评论