Scoping issue in Javascript

怎甘沉沦 提交于 2019-12-05 02:50:59

问题


I need to have some information about the Scoping issue in Javascript. I know that it spports lexical(static) scoping, but, does not it support dynamic scoping as well? If you know anything about the scoping in Javascript, would you please share them with me ?

Thanks


回答1:


I think you're confused because Javascript uses static scoping but at function-level, not at block level like usual structured languages.

var foo = "old";
if (true) {var foo = "new";}
alert (foo == "new")

So be careful, blocks don't make scope! That's why you sometimes see loops with functions inside just to enable variables whose scope is inside an iteration:

functions = [];
for(var i=0; i<10; i++) {
   (function(){
       var local_i = i;
       functions[local_i] = function() {return local_i;}
   })();
}
functions[2]() // returns 2 and not 10



回答2:


As far as I understood; Javascript has two kinds of variables which are global and local variables. But, suppose we have a variable called x, which is defined as global, and defined in the static parent of the scope of place where x is referenced. In this case, x takes the value of the global variable. Thus, global variable has higher priority than local ones. And, when there is no any global variables, x finds the declaration through the static chain which makes me think that Javascirpt is staticaly scoped language.

Am I right at above?



来源:https://stackoverflow.com/questions/327454/scoping-issue-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!