Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

javascript - 我可以从其他文件中访问变量吗?(Can I access variables from another file?)

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

(是否有可能使用在一个名为变量first.js称为另一个文件中second.js ?)

first.js contains a variable called colorcodes .

(first.js包含一个变量,名为colorcodes 。)

  ask by SAK translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared.

(正如Fermin所说,全局范围中的变量应该可以被声明后加载的所有脚本访问。)

You could also use a property of window or (in the global scope) this to get the same effect.

(您也可以使用的属性window或(在全球范围内), this得到同样的效果。)

// first.js
var colorCodes = {

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

};

... in another file ...

(...在另一个文件中......)

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

... in your html file ...

(...在你的html文件中......)

<script type="text/javascript" src="first.js"></script> 
<script type="text/javascript" src="second.js"></script> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...