简体   繁体   中英

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

var test='test string';

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

var a = 'a';
console.log(b);

b.js:

var b = 'b';
console.log(a);

Are you using top-down execution in your javascript files? 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...

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