javascript提升:首先要提升的是什么-变量或函数? [英] javascript hoisting: what would be hoisted first — variable or function?

查看:41
本文介绍了javascript提升:首先要提升的是什么-变量或函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我对javascript的吊装行为感到困惑,现在我被困住了.

Recently I was confused about javascript hoisting behavior and now I got stuck with that.

因此,有两个示例.

var alpha = 'alpha';

var beta = 'beta';

f(); //beta


var f = function f1() {
    console.log(beta);
};

function f() {
    console.log(alpha);
}

f(); // alpha

第一个按预期方式工作,因为在Javascript设置了词法环境时,函数声明将覆盖变量f(值为"undefined").

The first one is working as expected, because the function declaration overwrite our variable f (with value "undefined") when Javascript is set up the Lexical Environment.

但是第二个让我有点不明白.

But the second gives me a push, that I does not understand something.

var alpha = 'alpha';

var beta = 'beta';

f();  // - alpha


function f() {
    console.log(alpha);
}

var f = function f1() {
    console.log(beta);
};


f(); // beta

为什么变量 f 没有提升到输出代码的顶部,而之前却覆盖了我们提升的函数?为什么在第一个f" 调用中我收到"alpha".我认为这一定是一个错误,例如:"f不是函数",因为我以为在第一个f 调用中,f将是"undefined" .

Why the variable f did'nt hoisted to the top of out code, and overwrite our hoisted function before? Why in "first f" call I recieve "alpha". I think, that it must be an error like: "f is not a function", because in first f call I excepect, that the f would be "undefined".

推荐答案

给出 var foo = something ,只有变量声明被吊起.

Given var foo = something, only the variable declaration is hoisted.

这意味着 var foo 被吊起,但 foo = something 将按读取顺序运行.

This means that var foo is hoisted but the foo = something will run in the reading order.

给出 function foo(){} ,将同时声明变量声明.这将创建变量 foo 并为其提供函数的值.

Given function foo() {}, the variable declaration and function assignment are both hoisted. This creates the variable foo and gives it the value of the function.

如果同时具有以上两种情况,则需要两次声明变量(不产生任何其他影响),然后为该变量分配函数的值(这是唯一的赋值).

If you have both of the above, then you declare the variable twice (for no extra effect) and assign it the value of the function (as that is the only assignment).

所以在您的第二个示例中……

So in your second example…

函数声明被悬挂,所以 f();//-第一个f 调用.

The function declaration is hoisted, so f(); // - first f calls that.

函数表达式的赋值不是悬挂的,而是 f();.//**-第二个f 会以正常阅读顺序出现在第二个f 之后,因此第二次调用 foo()就会达到目标.

The assignment of the function expression is not hoisted, but f(); // ** - second f appears after it in normal reading order, so the second call to foo() hits that.

这篇关于javascript提升:首先要提升的是什么-变量或函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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