test(); //working
function test(){//do something}
这和(全局)变量对象有关吗?函数在执行过程开始之前是否将变量推送到变量对象?
更新:好的,我真正的问题是“提升”是如何工作的。要理解,您需要看一下javascript的执行上下文,是的,它与变量对象(属于执行上下文)有关。
function foo() { }
foo
自动提升到范围的顶部
这和(全局)变量对象有关吗?函数在执行过程开始之前是否将变量推送到变量对象?
不,这只是吊装。
考虑以下示例:
foo();
// ReferenceError: foo is not defined
(function(){
foo();
function foo (){
console.log("A");
};
})();
// A
(function(){
foo();
function foo (){
console.log("B");
};
})();
// B
foo();
// ReferenceError: foo is not defined
吊起只是将变量名称“提升”到作用域的顶部。
我的想法:
我从不将函数编写为:
function foo() { ... }
我更喜欢露骨,因为魔术行为很烂。我总是写函数为
var foo = function() { ... }
如果我觉得该函数需要一个名称,我会给它一个名称,但仍然使用 var
var foo = function foo() { ... }
@bfavaretto引起了有效的关注:
关于您的意见... var foo = function(){...}还将foo提升到顶部,但具有未定义的值。所以那里也隐含着东西
诚然,它确实葫芦foo
具有undefined
价值,但事情会如期望的一切工作。
foo();
// TypeError: undefined is not a function
// This is good. We don't want the above function to run like that.
// This is a fatal error; the script won't even continue to run as-is.
// Comment out the above line to get it to run.
var foo = function foo() {
console.log("foo");
};
var foo2 = function foo() {
console.log("foo2");
};
// Even with the same function name, these two functions will
// output the correct values.
foo(); // foo
foo2(); // foo2
综上所述,在同一个作用域中拥有两个具有相同名称标识符的功能是很愚蠢的。但是,即使您确实犯了一个错误并编写了类似的错误代码,但是如果您如上所述使用函数表达式,该代码仍然可以正常工作。如果您只是像原始问题中那样使用命名函数,则肯定不会。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句