2015-09-19 27 views
0

是不是功能abc()hoisted? 假设var abcfunction abc两者都是悬挂的优先?如何覆盖JavaScript中的函数提升?

var abc = 10; 
console.log(abc); 

abc(); 

function abc(){ 
    console.log("abc"); 
} 

为什么下面的代码显示错误“abc不是函数”?

+4

它与许多红旗,然后覆盖。无论哪个优先级更高,分配总是在之后发生。甚至更多 - 无论如何你都是在分配后立即检查。 – zerkms

回答

3

这相当于写

// hoisted stuff 
var abc; 
function abc(){ 
    console.log("abc"); 
} 
// end hoisted stuff 
// your code is now 
abc = 10; // abc now no longer a function 
console.log(abc); 
abc(); 
1

这是因为功能悬挂在Javascript功能。 You can read more about it here。它的基本含义是,如果您在代码中定义了一个函数,则Javascript在分析代码时会发现它,并假定它在该范围内定义。所以这个代码:

abc(); 

function abc(){ 
    console.log("abc"); 
} 

作品,如果你写道:

function abc(){ 
    console.log("abc"); 
} 

abc(); 

但是你已经通过显式定义abc重写的功能。 因此,它假定abc是您定义的变量。 如果调用abc()您定义的功能后,它甚至不会工作:

var abc = 10; 
console.log(abc); 

function abc(){ 
    console.log("abc"); 
} 

abc(); // still an error because abc is still considered a var 
console.log(abc); //prints 10 

通过定义具有相同的名称,你基本上是隐藏它的函数的变量。为了解决这个问题,你可以给他们不同的名称或使用函数表达式(就像给变量分配一个新值,并没有做吊装):

var abc = 10; 
console.log(abc); // prints 10 

abc = function abc() { // you are assigning a new value to abc 
    console.log("abc"); 
} 

abc(); // prints 'abc' 

请记住,当你使用函数表达式,函数名称只能在函数体内访问。

var a = function b() { console.log('b')} 
b() // Uncaught ReferenceError: b is not defined 
a() // prints 'b' 

在这种情况下,函数名然而,可以在函数体中使用递归调用:

function b(x) { return x > 2 ? x * b(x - 1) : 1 } 
b(4); // returns 12