Why is no ReferenceError being thrown if a variable is used before it’s declared?

本小妞迷上赌 提交于 2019-11-28 11:35:51

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');

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

This is due to Javascript variable declaration "hoisting".

A variable declared with var is visible everywhere in the function, so there's no Reference Error. However, it doesn't actually receive its value until you execute the statement that initializes it. So your second example is equivalent to:

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

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

alert('Completed');

In this rewrite, you can see that the variable exists when you perform the assignment to obj.func1. But since it doesn't yet have a value, you assign undefined to obj.func1. Assigning to func2 later doesn't change that.

Your func2 variable is not visible. That's why obj.func1 remains undefined.

var obj = {};
var func2 = function() {
    alert('func2');
    return "Test";
};
    
obj.func1 = func2;
   
alert('Completed');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!