JS作用域访问 [英] JS scope access

查看:47
本文介绍了JS作用域访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[更新],我确认不能这样做.

全部:

我对JS范围还很陌生,比如说我有一个定义为:

I am pretty new to JS scope, say I have a function defined as :

var scope = "scope inside global";
function out(){

    var scope = "scope inside out";

    function scopeaccess(){
        console.log(scope);
    }

    scopeaccess();
    return scopeaccess;
}
var sa = out();
sa();

输出都是从内到外",我想知道如何在scopeacess中访问从内到外"?或者我只是想确认没有办法做到这一点.

The outputs are both "scope inside out", I wonder how can I access "scope inside global" in scopeacess? Or I just want to confirm that there is no way to do that.

谢谢

推荐答案

我想知道我如何才能在scopeacess中访问全局范围内"?

I wonder how can I access "scope inside global" in scopeacess?

您根本无法.您需要为本地 var作用域使用不同的变量名,以便可以访问全局 scope 变量.当然,您也可以通过别名全局变量或显式传递其值来解决此问题,以便可以通过除 scope 变量之外的其他方式访问它.

You cannot at all. You would need to use a different variable name for the local var scope so that you can access the global scope variable. Of course, you can also work around this by aliasing the global variable, or by passing its value around explicitly, so that it can be accessed through other means than the scope variable.

在您的示例中,名称的选择可能只是为了说明正在发生的情况(闭包在词法上没有动态作用域),在实际脚本中,您不会

In your example, the names were probably only chosen to demonstrate what is going on (that closures are lexically not dynamically scoped), in actual scripts you wouldn't shadow the variables you need (or only by mistake).

这篇关于JS作用域访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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