如果在声明变量之前使用了变量,为什么不抛出ReferenceError? [英] Why is no ReferenceError being thrown if a variable is used before it’s declared?

查看:81
本文介绍了如果在声明变量之前使用了变量,为什么不抛出ReferenceError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决JavaScript中引发的引用错误的行为.

I’m trying to wrap my head around the behavior of reference errors thrown in JavaScript.

在下面的示例中,第二行引发 ReferenceError ,执行中断:

In the following example, a ReferenceError is thrown at the second line, and execution breaks:

var obj = {};
obj.func1 = func2;

alert('Completed');

在此示例中,尽管 obj.func1 仍然 undefined :

Whereas in this example, the code completes successfully, though obj.func1 remains undefined:

var obj = {};
obj.func1 = func2;

var func2 = function() {
    alert('func2');
};

alert('Completed');

我的假设是在第二行相同的地方抛出一个错误,如果不是这种情况,我希望 obj.func1 正确地引用func2 ,但我一直是双盲的.那到底是怎么回事?

My assumption was that an error would be thrown at the second line just the same, and when that wasn’t the case, I’d have expected obj.func1 to properly reference func2, but I’ve been double blind-sided. So what exactly is going on here?

推荐答案

var 已吊起;该变量存在于当前范围内.因此,第二个示例等效于:

var is hoisted; the variable exists throughout the current scope. Thus, the second example is equivalent to:

var obj;
var func2;

obj = {};
obj.func1 = func2;
func2 = function() {
    alert('func2');
}

alert('Completed');

因此,当您进行分配时,名称 func2 是已知的,但是 undefined .在第一个示例中,它是未知的,这会引发 ReferenceError .

Thus, when you do the assignment, The name func2 is known, but undefined. In the first example, it is unknown, which raises ReferenceError.

这篇关于如果在声明变量之前使用了变量,为什么不抛出ReferenceError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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