简体   繁体   中英

return value from js file

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?

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

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM