如何在JavaScript中提升名称解析顺序? [英] How hoisting name resolution order works in JavaScript?
问题描述
我遇到了一个有趣的测验
function bar() {
return foo;
foo = 10;
function foo() {}
var foo = '11';
}
alert(typeof bar());
我的解释是这样的(根据控制台错误:) :):
My interpretation is like this (Which is wrong according to console :) ):
var foo; // global variable
function bar(){
function foo(){}
var foo; // Here variable foo should override foo function
return foo; // (according to me foo should be variable with undefined value) What is going on here, How JavaScript resolve naming order ?
foo = 10;
foo = "11";
}
这是我正在阅读的参考这个
Here is a reference which I am reading this
在JavaScript中,名称以四种基本方式之一进入范围:
1.Language-defined:默认情况下,所有范围都给出名称this和arguments。
2.形式参数:函数可以具有命名形式参数,其范围限定为该函数的主体。
3.函数声明:它们的形式为函数foo(){}。
4.变量声明:这些声明采用var foo形式;
In JavaScript, a name enters a scope in one of four basic ways: 1.Language-defined: All scopes are, by default, given the names this and arguments. 2. Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function. 3. Function declarations: These are of the form function foo() {}. 4. Variable declarations: These take the form var foo;
他后来引用:
要记住的最重要的特殊情况是名称解析顺序。请记住,名称有四种方式可以输入给定的范围。我在上面列出的顺序是它们被解析的顺序。通常,如果已经定义了名称,则它永远不会被同名的另一个属性覆盖。这意味着函数声明优先于变量声明。这并不意味着对该名称的赋值将不起作用,只是声明部分将被忽略。
The most important special case to keep in mind is name resolution order. Remember that there are four ways for names to enter a given scope. The order I listed them above is the order they are resolved in. In general, if a name has already been defined, it is never overridden by another property of the same name. This means that a function declaration takes priority over a variable declaration. This does not mean that an assignment to that name will not work, just that the declaration portion will be ignored.
这是令人困惑的我,有人可以参考上面的例子来简化这个吗?
要点我想知道:
Which is confusing for me, Can anyone simplify this with reference to above example ? Main point I want to know :
- 如何没有
var
的变量在一个悬挂的函数内? - 在吊装过程中是否发生变量覆盖?
- How variables without
var
inside a function hoisted ? - Does variable overriding occurs during hoisting ?
推荐答案
让我们暂时离开函数 foo
。在函数内,如果在该函数内的任何位置声明变量,则声明将移动到函数的顶部。因此,它实际上是这样评估的
Lets leave the function foo
for the moment. Within a function, if a variable is declared anywhere inside that function, the declaration will be moved to the top of the function. So, it is actually evaluated like this
function bar() {
var foo;
return foo;
foo = 10;
foo = '11';
}
但是当你有一个同名的函数时,它会优先它将被评估类似于此
But when you have a function declared by the same name, it will take precedence and it will be evaluated similar to this
function bar() {
var foo = function() {};
return foo;
foo = 10;
foo = '11';
}
这就是为什么你得到函数
在警告框中。
That is why you are getting function
in the alert box.
这篇关于如何在JavaScript中提升名称解析顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!