Undefined and are not defined exceptions in JavaScript __javascript

Source: Internet
Author: User

Do not explain, directly on the code:

Console.log (xx);
Console.log (window.xx);

(where xx is a nonexistent variable)

When the XX variable is printed directly, a not defined exception is thrown directly and the execution is terminated.

However, the XX variable in the form of window.xx printed out, the lack of direct output of a undefined, and did not appear abnormal, you can continue to execute.


After reviewing the relevant documentation, you will know that the print undefined indicates that the variable has been declared but not assigned, and that the print is not defined exception indicates that the variable does not even have a declaration. This conclusion shows that the window.xx form implicitly declares the variable in the Window object.

This also explains why the following code can be run directly.

window.xx = 2;
Console.log (window.xx);

There is also a related problem, see Code:

function T1 () {
	console.log (str2);  Undefined
	var str2 = ' Mike ';
}
T1 ();
And

function T1 () {
	console.log (str2);  is not defined
	str2 = ' Mike ';
}
T1 ();

The first case involves JavaScript runtime, divided into lexical analysis stage and run phase, in the lexical analysis stage, first declared STR2 variable but no assignment, so in the run phase appeared undefined.

The second case cannot be declared str2 at the lexical analysis stage, because there is no var keyword declaration, so the exception is thrown directly at run time.


It is also important to note that any variable that does not use the Var declaration will eventually become the property of the Global Object window, as follows:

function T1 () {
	a =
	console.log (a);//10
	Console.log (WINDOW.A);//10
}
t1 ();



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.