用var

问题描述

为什么在第一种情况下会显示x是一个函数而不是未定义?

(() => {
    var x

    function x() {}

    console.log(x)
})()

> ƒ x() {}

(() => {
    var x = 1

    function x() {}

    console.log(x)
})()

> 1

解决方法

之所以发生这种情况,是因为JavaScript在提升过程中是如何工作的。带有function VARIABLENAME() {}的函数在变量的“ existence”调用下直接出现,并且变量更改值保留在其位置,但由于函数向上移动而相对向下移动。

第一组

(() => {
    var x

    function x() {}

    console.log(x)
})()

// This gets converted to:
(() => {
    var x // This variable exists

    x = function x() {} // Ya know that variable called x? well its a function

    console.log(x)
})()

第二组

(() => {
    var x = 1

    function x() {}

    console.log(x)
})()

// This gets converted to:
(() => {
    var x // the variable x exists

    x = function x() {} // Functions are moved to the top,under variable declarations
    
    x = 1 // x is now the value 1

    console.log(x)
})()

,

提升是在编译过程中将变量(仅在声明的左侧)或函数声明移至相应环境顶部的行为。

在代码执行之前,JavaScript引擎会在创建阶段为变量和函数分配内存。

您的第一个示例就像您写的那样得到解释:

onMeasure(widthMeasureSpec: Int,heightMeasureSpec: Int)

您的第二个示例的解释与您编写的稍有不同:

// creation phase start
var x = undefined;
function x() {}; // a function is fully hoisted. So x references the function.
// creation phase end

// execution phase start
console.log(x); // therefore x is a function
// execution phase end

还有一件有趣的事情要知道: 如果您这样编写第一个示例...

// creation phase start
var x = undefined;
function x() {}
// creation phase end

// execution phase start
x = 1;
console.log(x); // therefore x got overwritten,therefore 1
// execution phase end

...函数声明的提升没有发生,因为引擎看到的第一件事既不是var也不是函数!