箭头功能是否比普通功能具有更高的优先级?

Neo*_*eon 8 javascript

以下两个片段均显示“箭头”。我想知道为什么。如果箭头函数具有相同的名称,它们的优先级是否比普通函数高?

function increment(){
    alert("normal")
}


var increment = () => {
    alert("arrow")
}

increment(); //prints arrow
Run Code Online (Sandbox Code Playgroud)
var increment = () => {
    alert("arrow")
}


function increment(){
    alert("normal")
}


increment(); //prints arrow
Run Code Online (Sandbox Code Playgroud)

mea*_*gar 9

这与箭头功能无关。相反,常规函数(和var声明)被悬挂;无论您在何处编写它们,它们都将移至其作用域的顶部。实际上,两个代码示例完全相同,如下所示:

var increment; // hoisted

function increment() { // hoisted
    alert("normal")
}

increment = () => { // the assignment itself is unaffected
    alert("arrow")
}

increment(); //prints arrow
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,的赋值部分都提升的函数和声明之后var increment = ...发生。无论您在哪里实际编写声明,它都将悬挂在执行分配给变量的行的上方。varfunction increment() { }increment

这就是为什么下面的代码仍然有效,尽管显然是被定义的功能使用它:

increment(); //prints normal

function increment(){
    console.log("normal")
}
Run Code Online (Sandbox Code Playgroud)

如果要比较类似,你需要比较var increment = () => { ... }var increment = function () { ... },即两个任务。结果看起来像这样:

var increment = () => { console.log('arrow'); }
var increment = function () { console.log('normal'); }

increment(); # normal
Run Code Online (Sandbox Code Playgroud)

var increment = function () { console.log('normal'); }
var increment = () => { console.log('arrow'); }

increment(); # arrow
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,都只有一个悬挂的var increment;声明,然后分配以它们被写入的顺序发生,这意味着最后一个分配将获胜。


顺便说一句,这是首选而let x = () => { }不是“旧的”样式函数声明的主要原因之一。let没有吊起,因此该功能从您自然希望的时间点开始就存在,而不是跳到示波器的顶部。