JS variable defines the difference between Var and no Var in--fn

Source: Internet
Author: User
Tags define local

A global object is built into the JS runtime.

This global object is related to the operating environment. In the browser runtime environment. Global is the Window object.
In the Nodejs. The global object is a global object.



When you use a non-defined variable directly in the browser environment,
For example foo=123; foo, the variable is automatically declared as a global variable. The variable reference is automatically attached to the global object, which is the Window object, and you can try to verify it by using the properties that are equivalent to the globals.

Such as:

<! DOCTYPE html>

  

In the body of the function defined under the Global object, without the variable declared by Var, first, it tries to chain in the current scope (as declared in the method, then the current scope chain represents the global scope and the method local scope etc ... ) to parse the variable; If the variable is found in any current scope chain, the variable is executed, and if the variable is not found, it is defined as a global variable and assigned to a global object (that is, the topmost object of the current scope chain, such as a Window object).

The test code is as follows:

<! DOCTYPE html>

So it is recommended that in FN Remember to define local variables to VAR, global variables do not VAR (note that there is no variable with the same name in the scope chain).

JS variable defines the difference between Var and no Var in--fn

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.