JavaScript吊装说明 [英] JavaScript hoisting explanation

查看:53
本文介绍了JavaScript吊装说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下摘要之间有什么区别?

What is the difference between below snippets?

var a = 0;
function b(){
    a = 10;
    return function a(){};
}
b();
console.log(a);  // => 10

var a = 0;
function b(){
    a = 10;
    return
    function a(){};
}
b();
console.log(a);  // => 0

这与JavaScript提升有关,但是我对该概念的理解却给出了完全相反的输出.

It has something to do with JavaScript hoisting, but my understanding of the concept gives exactly the opposite output.

推荐答案

return function a(){};

此处function ...是一个表达式.准确地说,是命名函数表达式.此处的a没什么大不了,它只是为匿名函数提供了

Here function ... is an expression. A named function expression to be precise. The a here doesn't matter much, it just gives the anonymous function a .name, but it's still just a function expression that you're returning.

return 
function a(){};

这等效于:

return;
function a(){};

此处function a是声明,而不是表达式.它被吊起,在作用域中创建本地名称a,遮盖了外部a. IE.它等效于:

Here function a is a declaration, not an expression. It is hoisted, creating a local name a in the scope, shadowing the outer a. I.e. it is equivalent to:

function b(){
    var a = function () {};
    a = 10;
    return;
}

这篇关于JavaScript吊装说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆