Can I access variables from another file?

2019-01-01 15:42发布

Is it possible to use a variable in a file called first.js inside another file called second.js?

first.js contains a variable called colorcodes.

7条回答
旧人旧事旧时光
2楼-- · 2019-01-01 15:43

You can export the variable from first file using export.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
export { colorCode };

Then, import the variable in second file using import.

//second.js
import { colorCode } from './first.js'

export - MDN

查看更多
不再属于我。
3楼-- · 2019-01-01 15:51

I came across amplify.js. It's really simple to use. To store a value, let's call it "myValue", you do:

amplify.store("myKey", "myValue")

And to access it, you do

amplify.store("myKey")
查看更多
其实,你不懂
4楼-- · 2019-01-01 15:58

I did like what answer above said but although, it didn't worked with me

because I was declaring these variables inside JQuery $( document ).ready()

so make sure you declare your variables inside the <script> tag not somewhere else

查看更多
初与友歌
5楼-- · 2019-01-01 16:03

If you store your colorcodes in a global variable you should be able to access it from either javascript file.

查看更多
荒废的爱情
6楼-- · 2019-01-01 16:04

As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared. You could also use a property of window or (in the global scope) this to get the same effect.

// first.js
var colorCodes = {

  back  : "#fff",
  front : "#888",
  side  : "#369"

};

... in another file ...

// second.js
alert (colorCodes.back); // alerts `#fff`

... in your html file ...

<script type="text/javascript" src="first.js"></script> 
<script type="text/javascript" src="second.js"></script> 
查看更多
牵手、夕阳
7楼-- · 2019-01-01 16:04

This should work - define a global variable in firstfile and access it from secondfile:

<script src="/firstfile.js"></script>
<script src="/secondfile.js"></script>

firstfile.js:

var colors = {
   text:'#000000',
   background:'#aaaaaa',
   something_else:'blue'
};

secondfile.js:

do_something_with(colors.background);

Note that the order in which you load the script files is significant for some browsers (IE6 for sure, maybe others)

查看更多
登录 后发表回答