在JavaScript中指定全局上下文 [英] Specify global context in JavaScript

查看:98
本文介绍了在JavaScript中指定全局上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,是否可以指定在未定义局部变量时将使用的全局上下文?

示例:

 (function foo(){
console.log(bar);
})();

它实际上会打印 window.bar



我可以以某种方式更改全球范围吗?像这样:

  var myGlobalContext = {bar:foo}; 

(function foo(){
console.log(bar);
})。applyWithGlobal(myGlobalContext);

它应该打印 myGlobalContext.bar



或者将这个作为全局上下文吗?



我希望这个例子足够清楚。

解决方案

最接近你能做的就是使用<$ c

$ p $ var $ myGlobalContext = {bar:foo}; $ c $> 语句。

with(myGlobalContext)
{
console.log(bar);
}

这与更改全局上下文不同,因为其他全局变量在 myGlobalContext 中找不到。



通常, code>声明为错误 ,但听起来你的用例可能是合理的。


In JavaScript, is it possible to specify the global context which will be used if a local variable isn't defined?

Example:

(function foo() {
    console.log(bar);
})();

It will actually print window.bar.

Can I somehow change the global context? Something like this:

var myGlobalContext = { bar: "foo" };

(function foo() {
    console.log(bar);
}).applyWithGlobal(myGlobalContext);

It should print myGlobalContext.bar.

Or attach this to be the global context?

I hope the example is clear enough.

解决方案

The closest thing you can do is mask the global variables using a with statement.

var myGlobalContext = {bar: "foo"};

with(myGlobalContext)
{
    console.log(bar);
}

This is not the same as changing the global context, because other globals that aren't found in myGlobalContext will still exist.

In general, the with statement is bad, but it sounds like your use case might be one where it makes sense.

这篇关于在JavaScript中指定全局上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆