开发者

Javascript function-level scope [closed]

开发者 https://www.devze.com 2023-04-01 13:41 出处:网络
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely solicit debate, a
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel 开发者_如何转开发that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

This is just a curiosity. But It is something that i would like to know.

I know that Javascript 1.7 support block scoping with let keyword.

But Why Javascript has been initially desinged with function-level scope instead of block scope?


A reasonable guess (but only a guess) could be that the very earliest iterations of the language did not have a var keyword but depended on a variable implicitly being created when it was assigned to. This is quite common for simple scripting languages -- many of them have to retrofit some explicit declaration mechanism as they mature and begin being used for large projects. Under this assumption, in order for code such as

if( bla bla bla ) {
  a = 24 ;
} else {
  a = blop.blop();
}
alert(a);

it wouldn't do if the implicit declarations of a were to be trapped by the braces instead of being visible at the alert. Thus, function-level scope.

Now imagine that by the time var was added, the assumption of function-level scope had already become entrenched in the specification and implementation of the language ...

0

精彩评论

暂无评论...
验证码 换一张
取 消