最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - return value from js file - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Mar 4, 2013 at 12:15 steosteo 4,6562 gold badges36 silver badges66 bronze badges 1
  • 2 not return, but you can assign it as a property of window. – John Dvorak Commented Mar 4, 2013 at 12:16
Add a ment  | 

3 Answers 3

Reset to default 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 remended)

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

发布评论

评论列表(0)

  1. 暂无评论