ReferenceError and the global object

不问归期 提交于 2019-12-17 06:51:29

问题


In javascript window is the global object, which means every object in the global scope is a child of window. So why I get this result:

console.log(window.foo); // No error, logs "undefined".
console.log(foo);        // Uncaught ReferenceError: foo is not defined.

Fiddle

Those two lines should be the same, shouldn't they?


回答1:


Because with window.foo you are explicitly looking for foo property of window object which is not the case in latter option. In the latter option, if foo isn't defined, you should as developer be able to know that it isn't defined and get the clear error warning rather than interpreter setting it to undefined on its own (like first case) which will lead to unexpected results.

Reference Error:

Represents an error when a non-existent variable is referenced. A ReferenceError is thrown when trying to dereference a variable that has not been declared.

Take a look at this article for more info:

  • Understanding JavaScript’s ‘undefined’

Quoting from above article:

A Reference is considered unresolvable if its base value is undefined. Therefore a property reference is unresolvable if the value before the dot is undefined. The following example would throw a ReferenceError but it doesn’t because TypeError gets there first. This is because the base value of a property is subject to CheckObjectCoercible (ECMA 5 9.10 via 11.2.1) which throws a TypeError when trying to convert Undefined type to an Object.

Examples:

var foo;
foo.bar; //TypeError (base value, foo, is undefined)
bar.baz; //ReferenceError (bar is unersolvable)
undefined.foo; //TypeError (base value is undefined)

References which are neither properties or variables are by definition unresolvable and will throw a ReferenceError, So:

foo; //ReferenceError



回答2:


In your first example (window.foo) you are accessing a property of the window object. JavaScript returns "undefined" for when you are trying to access a non existent property of a object. It's designed that way.

In the second example you are referencing a variable directly, and since it does not exists an error is raised.

It's just the way JavaScript is designed and works.




回答3:


In JavaScript you can assign object fields on the fly like that, so window.foo is nearly (see comments below) equivalent to var foo; when defined in the global context, whereas just calling foo out of the blue makes the browser panic 'cause it down't even know which object to look in. Notice, if you do:

//when in global context, 'var' sets a property on the window object
var foo;

console.log(foo);
//it will then also log `undefined` instead of throwing the error.

//if you then do:
foo = "abbazabba";

console.log(window.foo);
// it will return "abbazabba" 


来源:https://stackoverflow.com/questions/10102862/referenceerror-and-the-global-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!