JavaScript scope

JavaScript scope

In JavaScript, objects and functions are also variables.

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

JavaScript function scope: The scope is modified within the function.


#In JavaScript, variables declared with var actually have scope.

If a variable is declared inside the function body, the scope of the variable is the entire function body, and the variable cannot be referenced outside the function body:

'use strict';function foo () {
var x = 1;
x = x + 1;
}

x = x + 2; // ReferenceError! Unable to reference variable x
# outside the function body

##If two different functions declare the same variable, the variable will only work within the respective function body. In other words, variables with the same name inside different functions are independent of each other and do not affect each other:

'use strict';function foo() {var x = 1;
x = x + 1;
}function bar() {
var x = 'A';
x = x + 'B';
}

##JavaScript Local scope

Variables are declared within the function, and the variables are local scope.

Local variables: can only be accessed inside the function.

// The carName variable cannot be called here

function myFunction() {
var carName = "Volvo";
// The carName variable can be called within the function
}

Note:

Because local variables only act within the function, different functions can use variables with the same name.

Local variables are created when the function starts executing, and will be automatically destroyed after the function is executed.

Global scope

Variables not defined within any function have global scope. In fact, JavaScript has a global object window by default, and variables in the global scope are actually bound to a property of window:

'use strict';

var course = 'Learn JavaScript';

##alert(course); // 'Learn JavaScript'

alert(window. course); // 'Learn JavaScript'

Therefore, directly accessing the global variable course is exactly the same as accessing window.course.

    php中文网(php.cn) 

全局变量在任何脚本和函数内均可访问。

JavaScript variable life cycle

JavaScript variable life cycle is initialized when it is declared.

Local variables are destroyed after the function is executed.

Global variables are destroyed after the page is closed.

Function parameters

Function parameters only work within the function and are local variables.


Continuing Learning
||
php中文网(php.cn)
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!