Understanding Scope of variables in JS

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/javascript_meng/article/details/99987804

JavaScript Scope

Scope is a collection of accessible variables.

In JavaScript, objects and functions is also variable.

In JavaScript, the scope is accessible variables, objects, collection of functions.

JavaScript function scope: Scope modified within the function.

Variable scope division

Variables can either be global, it can be localized.

JavaScript globals

Variables defined outside the function, i.e. a global variable.
Global variables have a global scope: pages all scripts and functions can be used.

Examples

var carName = " hi";
// 此处可调用 carName 变量
function myFunction() {
    // 函数内可调用 carName 变量
}

If the variable is not declared (not using the var keyword) within a function, the variable is a global variable.
The following examples carName within a function, but as a global variable.

Examples

// 此处可调用 carName 变量
function myFunction() {
    carName = "hi";
    // 此处可调用 carName 变量
}

JavaScript local scope

Variables declared within a function, variables local scope.
Local variables: can only be accessed within the function.

Examples

// 此处不能调用 carName 变量
function myFunction() {
    var carName = "hi";
    // 函数内可调用 carName 变量
}

Because the local variable is only applied to the function, the function may use different variables of the same name.
Local variables are created when the function begins execution, after the implementation of the function of local variables are automatically destroyed.

Guess you like

Origin blog.csdn.net/javascript_meng/article/details/99987804