变量是静态的还是动态的“范围”变量。在JavaScript中? [英] Are variables statically or dynamically "scoped" in javascript?

查看:80
本文介绍了变量是静态的还是动态的“范围”变量。在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者更具体到我需要的东西:

Or more specific to what I need:

如果我从另一个函数中调用一个函数,它是否会从调用函数中提取变量,或者从上面的水平?例如:

If I call a function from within another function, is it going to pull the variable from within the calling function, or from the level above? Ex:

myVar=0;

function runMe(){
    myVar = 10;
    callMe();
}

function callMe(){
   addMe = myVar+10;
}

如果通过runMe()调用callMe(),myVar最终会是什么? ?

What does myVar end up being if callMe() is called through runMe()?

推荐答案

杰夫是对的。请注意,这实际上不是静态作用域的一个很好的测试(JS确实有)。更好的是:

Jeff is right. Note that this is not actually a good test of static scoping (which JS does have). A better one would be:

myVar=0;

function runMe(){
    var myVar = 10;
    callMe();
}

function callMe(){
   addMe = myVar+10;
}

runMe();
alert(addMe);
alert(myVar);

在静态范围的语言(如JS)中,警告10和0. var myVar( runMe中的局部变量)会影响该函数中的全局myVar。但是,它在callMe中没有任何效果,因此callMe使用仍为0的全局myVar。

In a statically scoped language (like JS), that alerts 10, and 0. The var myVar (local variable) in runMe shadows the global myVar in that function. However, it has no effect in callMe, so callMe uses the global myVar which is still at 0.

在动态范围的语言中(不同) JS),callMe将从runMe继承范围,因此addMe将变为20.请注意,myVar在警报时仍然为0,因为警报不会从任一函数继承范围。

In a dynamically scoped language (unlike JS), callMe would inherit scope from runMe, so addMe would become 20. Note that myVar would still be 0 at the alert, because the alert does not inherit scope from either function.

这篇关于变量是静态的还是动态的“范围”变量。在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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