【问题标题】:Can someone explain the output of following code?有人可以解释以下代码的输出吗?
【发布时间】:2020-05-29 22:49:34
【问题描述】:

var employeeId = 'abc123';
function foo() {
	employeeId = '123bcd';
	return;

	function employeeId() {
		var x = 0;
	}
}
foo();
console.log(employeeId); //abc123

问题是基于提升。我们在这里在 console.log 中打印employeeId。有人能解释一下上面代码的输出吗?

【问题讨论】:

    标签: javascript ecmascript-6 hoisting


    【解决方案1】:

    根据提升规则,在同一个闭包中,function 声明几乎等同于:

    var employeeId = 'abc123';
    
    function foo() {
    	var employeeId = function () { // hoisted from the function below
    		var x = 0;
    	}
    
    	employeeId = '123bcd';
    	return;
    
    	// function employeeId() {
    	// 	var x = 0;
    	// }
    }
    
    foo();
    console.log(employeeId); //abc123

    所以外部范围 employeeId 没有被更改,因为它在 foo 中被隐藏了 功能范围。

    【讨论】:

    • 天哪,这太微妙了。这个问题正在深入挖掘 Javascript 的复杂性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    相关资源
    最近更新 更多