[英]how to pass variable to another js file
I am trying to pass a variable from a.js file to b.js file. 我正在尝试将变量从a.js文件传递到b.js文件。
a.js a.js
var test='test string';
b.js b.js
alert(test);
I am sure a.js is included in my html before b.js but I still got ' test
' is not defined error. 我确定a.js包含在b.js之前的html中,但是我仍然遇到' test
'未定义的错误。 Are there anyway to debug this? 反正有调试吗? Thanks a lot! 非常感谢!
要确保将测试分配给全局范围,请执行以下操作:
window.test = 'test string';
I don't think you are as much passing a variable in this case as making it accessible. 在这种情况下,我认为传递变量不是使它易于访问。 At some point you may want to look at this (scope vs. context) . 在某些时候,您可能要看一下(范围与上下文) 。 It may seem like a bit much this early on, but it will come in handy sooner than you think. 可能看起来有点早,但是比您想像的要早得多。
To debug: 要调试:
a.js: a.js:
var a = 'a';
console.log(b);
b.js: b.js:
var b = 'b';
console.log(a);
Are you using top-down execution in your javascript files? 您是否在JavaScript文件中使用了自上而下的执行方式? Using the global scope - unless its a constant or a helper function - its almost always a bad idea... 使用全局范围-除非它是常量或辅助函数-否则几乎总是一个坏主意...
At a minimum, define functions if not classes and pass variables between those instead... 至少要定义函数(如果不是类的话),并在它们之间传递变量……
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.