[英]return value from js file
I have two js
file in my html
page . 我的html
页面中有两个js
文件。 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? 我可以将var
插入function($,varname)
, return
它的值并在另一个文件中使用它吗?
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. 我们假设我们需要将值“Bacon”发送到另一个脚本。
(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. 请注意,这些文件在javascript中无关紧要:如果两个文件连接在一起,那么您的页面将会起作用(如果您使用“严格”,则除外)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.