javascript - Javascript 中的名称解析?

标签 javascript hoisting

<分区>

我正在读这个article我有一些问题请问:

考虑这段代码:

1:   var a = 1;
2:   function b () {
3:       a = 10;
4:       return;
5:       function a() {}
6:   }
7:   b();
8:   alert(a);

这将提醒 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;.

第 3 行假设更改全局 a 的值。 但是函数 a(){...} 优先于内部声明(如果我理解正确的话) 这就是为什么警报 1

附注如果我删除第 5 行,它会提醒第 10 行。

In general, if a name is already defined, it will never be redefined by another entity with the same name. That is the function declaration has a priority over the declarations of the variable with the same name. But this does not mean that the value of a variable assignment does not replace the function, just its definition will be ignored.

我不明白那部分:

But this does not mean that the value of a variable assignment does not replace the function

请问 2 个问题:

  • 我是否正确理解了发出警报的原因 1

  • 上面一行是什么意思? (被误解的部分)

谢谢。

最佳答案

Did I understand correctly the reason for alerting 1

"But this does not mean that the value of a variable assignment does not replace the function"
What does the above line means ? (the misunderstood part)

这只是意味着虽然名称为 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);

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);

关于javascript - Javascript 中的名称解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12287049/

相关文章:

javascript - Vue.js 中的循环变量与 AngularJS 类似

javascript - 显示正在加载处理器的异常行为

javascript - 在命名空间内设置标准 JavaScript 原型(prototype)继承?

javascript - const 和 let 会让 IIFE 模式变得不必要吗?

javascript - 提交到 iframe 后清除表单

javascript - jQuery 用户界面 - 错误 : cannot call methods on dialog prior to initialization; attempted to call method 'open'

javascript - 无法遍历 DOM 来查找相关输入

当函数作为参数传递时,Javascript 函数提升不适用?

Javascript 提升、函数声明

javascript - 变量提升示例