我有一个名为 foo 的变量和名为 foo 的函数。
//variable followed by function declaration
var foo="bar";
function foo(){
return "bar";
}
//function declaration followed by variable
function foo(){
return "bar";
}
var foo="bar";
//When I call foo it returns string bar;
//When I enquired foo() it throws error
这里发生了什么?为什么变量名会覆盖函数声明?
最佳答案
When I call
foo
it returns stringbar
;
函数声明为 hoisted到他们范围的顶部。函数定义被编译器移到了上面。然后变量被覆盖为字符串。
代码等效于
function foo() {
return "bar";
}
// Overwriting the value
var foo = "bar"
因此,在这两种情况下,输出均为'bar'
。
请注意function expressions没有被吊起。
有关函数提升的更多信息,请参阅 Javascript function scoping and hoisting
When I enquired
foo()
it isundefined
foo
这里不是一个函数,它是一个字符串。因此,foo()
会抛出错误
Uncaught TypeError: a is not a function(…)
关于javascript - 当变量和函数同名时,引用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40077969/