可以在javascript中创建全局作用域闭包吗?
目标是允许全局变量(如可以在javascript中创建全局作用域闭包吗?,javascript,scope,global-variables,Javascript,Scope,Global Variables,目标是允许全局变量(如currentAccount)根据执行上下文同时引用多个值 var context = new Context(); context.currentAccount = "mine"; context.execute(function() { // any code in or called by this function // needs access to the `currentAccount` variable // for example
currentAccount
)根据执行上下文同时引用多个值
var context = new Context();
context.currentAccount = "mine";
context.execute(function() {
// any code in or called by this function
// needs access to the `currentAccount` variable
// for example
var model = new Model();
model.doSomething(); // model needs to be able to refer to `currentAccount`
});
context = new Context();
context.currentAccount = "yours";
context.execute(function() {
...
model.doSomething(); // `currentAccount` => "yours"
});
至于原因,我正在使用的应用程序从未打算允许用户同时使用多个帐户。现在看来,这样做可能是有道理的。这些全局会话变量中有三个或四个在整个代码库中广泛使用。在各自的iframe中执行每个“上下文”是否最简单?我建议您重新编写代码,以便根据需要传递
currentAccount
引用(要么将其传递给模型构造函数,要么传递给模型.doSomething()
调用,以适合您的模型为准),而不是像您正在尝试的那样尝试解决它。这种方法感觉太具侵入性了。代码库中几乎每个类都引用这些全局会话变量(类似于rails中的current_user
方法——想象一下必须将用户作为参数传递给每个方法调用)。这就是为什么您可以将其作为构造函数的参数或实例的属性添加,并将对全局变量的引用更改为对实例属性的引用。这正是为什么首先避免使用全局变量的原因。