Roy*_*mir 3 javascript hoisting
我正在阅读这篇文章,我有一些问题请:
考虑这段代码:
1: var a = 1;
2: function b () {
3: a = 10;
4: return;
5: function a() {}
6: }
7: b();
8: alert(a);
Run Code Online (Sandbox Code Playgroud)
这将提醒1.(我的问题是为什么?)
文章指出它与名称解析有关.
名称解析(根据文章)由此订单决定:
1. Internal mechanisms of language: for example, in all scopes are available “this” and “arguments”.
2. Formal parameters: the functions can be named as the formal parameters, which scope is limited to the function body.
3. Function declarations: declared in the form of function foo() {}.
4. Variable declarations: for example, var foo;.
Run Code Online (Sandbox Code Playgroud)
第3行假设改变全局a的值.但函数a(){...}在声明内部有一个优点(如果我理解正确的话)那就是为什么警报1
ps如果我删除第5行,它将提醒10.
通常,如果已定义名称,则永远不会由具有相同名称的其他实体重新定义该名称.也就是说,函数声明优先于具有相同名称的变量的声明.但这并不意味着变量赋值的值不会替换函数,只会忽略它的定义.
我不明白那一部分:
但这并不意味着变量赋值的值不会替换函数
所以请2个问题:
我是否正确理解了警报的原因1
上述内容是什么意思?(被误解的部分)
谢谢.
我是否正确理解了警报的原因1
是
"但这并不意味着变量赋值的值不会取代函数"
上述行的含义是什么?(被误解的部分)
它只是意味着虽然a已经定义了具有名称的函数,但a = 10仍然会执行,即在该行之后a不再引用函数,而是执行10.
我假设他们想稍微放松前面的语句并避免人们错误地认为因为函数声明首先执行,所以不再进行赋值.
函数和变量声明被提升到范围的顶部.所以代码相当于:
1: var a = 1;
2: function b () {
3: function a() {}
4: a = 10;
5: return;
6: }
7: b();
8: alert(a);
Run Code Online (Sandbox Code Playgroud)
function a() {...}a在本地范围内创建一个符号(变量),它的值是完全相同的函数.然后,下一行,a = 10;为该符号分配一个新值,即一个数字.
var a = 1;
function b () {
function a() {} // creates a new local symbol `a`, shadowing the outer `a`
// until here, `a` refers to the function created
// created by the above declaration
a = 10; // now a new value is assigned to the local symbol/variable `a`
// from here on, `a` is `10`, not a function
return;
}
b();
alert(a);
Run Code Online (Sandbox Code Playgroud)