JavaScript通常遵循函数作用域,即变量只能在声明它们的函数中访问.
打破此约定并使变量在函数范围外可访问的方法之一是使用全局窗口对象,例如
window.myVar = 123;
Run Code Online (Sandbox Code Playgroud)
我的问题是JavaScript/jQuery中有没有其他方法可以在函数范围之外访问变量?
没有变量声明,没有.显然,您可以在外部作用域中声明一个变量,以便所有后代作用域都可以访问它:
var a; // Available globally
function example() {
a = "hello"; // References a in outer scope
}
Run Code Online (Sandbox Code Playgroud)
如果您没有处于严格模式,则只需删除var关键字即可.这相当于您的示例:
// a has not been declared in an ancestor scope
function example() {
a = "hello"; // a is now a property of the global object
}
Run Code Online (Sandbox Code Playgroud)
但这是非常糟糕的做法.如果函数在严格模式下运行,它将抛出一个引用错误:
function example() {
"use strict";
a = "hello"; // ReferenceError: a is not defined
}
Run Code Online (Sandbox Code Playgroud)