Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
可以在javascript中创建全局作用域闭包吗?_Javascript_Scope_Global Variables - Fatal编程技术网

可以在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
方法——想象一下必须将用户作为参数传递给每个方法调用)。这就是为什么您可以将其作为构造函数的参数或实例的属性添加,并将对全局变量的引用更改为对实例属性的引用。这正是为什么首先避免使用全局变量的原因。