[英]Why the second console.log() gives 2, insted of 1?
为什么第二个console.log()
给出2
,则为1
?
function f() { console.log(2); } f(); (function() { f(); f = function() { console.log(1); } })();
在javascript中,函数声明悬挂在封闭范围内,但分配没有。 第二个调用中的内容不是函数声明-您只是在更改现有变量的值。 如果您想在第二个调用中使用f()
的提升版本,则需要执行以下操作:
function f() { console.log(2); } f(); (function() { f(); function f() { // this is a function declaration so it will be hoisted to the top console.log(1); } })();
您正在呼叫f(); 在函数表达之前的IIFE中。 如果移动第二个f(); 在表达式下方调用,您将获得期望的结果。
function f() {
console.log(2);
}
f();
(function() {
f = function() {
console.log(1);
}
f();
})();
第二个“ console.log(1)”输出2,因为它实际上是您正在调用的第一个“ console.log(2)”-两次。 您从未真正调用过会触发“ console.log(1)”的函数。 这是正在发生的事情的更具代表性的示例:
function f(value) { console.log(value); } f('a'); (function() { f('b'); f = function() { console.log('c'); } // unless you call "f()" at this point, this would not work. The "f = func ... " doesn't get hoisted. })();
注意输出如何为“ a”和“ b”,但从未记录“ c”。 函数的变量分配不会被取消,我假设您会认为会发生?
希望能有所帮助。
那是因为函数声明被执行了两次。
仅供参考-函数声明被吊起,但函数表达式没有被吊起。
function f() { // function declaration console.log(2); } f(); // 2 (function() { f(); // 2 f = function() { // function expression console.log(1); } // you can use function expression here now that it is defined f(); // 1 })(); // will output: // 2 // 2 // 1
阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.