3

I have two js file in my html page . If the first one begins with :

 (function($){
   ..  
   ..
   }(jQuery));

can I insert a var into function($,varname) , return it's value and use it in the other file?

1
  • 2
    not return, but you can assign it as a property of window. Commented Mar 4, 2013 at 12:16

3 Answers 3

3

You need a global variable for this. You can do this in one of a few ways. Let's assume we need to send the value "Bacon" to the other script.

(function($){
   window.myScriptsExports = "Bacon";
}(jQuery));

// OR

var myScriptsExports = (function($){
   // other code
   return "Bacon";
   // NO other code
}(jQuery));

// OR (not really recommended)

(function($){
   // other code
   $.myScriptsExports = "Bacon";
   // other code
}(jQuery));
Sign up to request clarification or add additional context in comments.

Comments

2

You can improve the code by using global namespace which goes like:

    (function($,global){
       var _obj = {};
       _obj.property1 = 'Property1';
       _obj.function1 = function() { console.log('Function 1');};
       global.myObject = _obj;
     }(jQuery,window));

     //accessing
     window.myObject.property1
     //or
     window.myObject.function1()

Comments

1

Supposing your function is synchrone, you may set a global function :

   (function($){
   .. 
      var myvar = 666; 
      window.getMyVar = function() {
         return myvar;
      };
   ..
   }(jQuery));

and you can use it from the other function if the second file is imported after this one :

   (function($){
   .. 
      var myprevisouslysetvar = window.getMyVar();
   ..
   }(jQuery));

Note that the files doesn't matter in javascript : your page would work the same (apart details if you have "use strict") with both files concatenated.

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.