通过两端代码介绍JavaScript如何声明全局变量
在函数外定义全局变量
var oneVariable; function setVariable(){ oneVariable = "Variable set from within a function!"; } function getVariable(){ alert(oneVariable); // Outputs "Variable set from within a function!" }
或者附加到window对象上
function setValue() { window.myValue = "test"; } function getValue() { alert(window.myValue); // "test" (assuming setValue has run) }