JavaScript Advanced – Day 1
Learn scope, variable promotion, closures and other language features, deepen the understanding of JavaScript, master the concise syntax of variable assignment, function declaration, reduce the redundancy of code.
- Understand the impact of scope on program execution
- Ability to analyze the scope of program execution
- Understand the nature of closures and use them to create isolation scopes
- What about variable promotion and function promotion
- Master arrow functions, parsing remaining parameters and other concise syntax
First, scope
Understand the impact of scope on program execution and the look-up mechanism of scope chains, and use closure functions to create isolated scopes to avoid global variable contamination.
Scope specifies the “scope” that a variable can be accessed. A variable cannot be accessed without this “scope”. The scope is divided into global scope and local scope.
1.1 Local scope
Local scopes are divided into function scopes and block scopes.
Function scope
Variables declared inside a function can only be accessed inside the function, not directly outside it.
<script>
// declare counter
function counter(x, y) {
// The variable declared inside the function
let s = x + y;
console.log(s); / / 18
}
// call it counter
counter(10.8);
// Access the variable s
console.log(s); / / an error
</script>
Copy the code
Conclusion:
- Variables declared inside a function cannot be accessed outside the function
- Function parameters are also local variables inside the function
- Variables declared inside different functions cannot be accessed from each other
- After the function is executed, the variables inside the function are actually cleared
Block scope
Code wrapped in {} in JavaScript is called a code block, and variables declared inside the block will be inaccessible.
<script>
{
// Age can only be accessed in this code block
let age = 18;
console.log(age); / / normal
}
// Out of scope of age
console.log(age); / / an error
let flag = true;
if(flag) {
// STR can only be accessed in this code block
let str = 'hello world! ';
console.log(str); / / normal
}
// Out of scope of age
console.log(str); / / an error
for(let t = 1; t <= 6; t++) {
// t can only be accessed in this code block
console.log(t); / / normal
}
// out of scope of t
console.log(t); / / an error
</script>
Copy the code
In JavaScript, there are constants in addition to variables. The essential difference between constants and variables is that [constants must have values and cannot be reassigned]. When constants are objects, their properties and methods can be reassigned.
<script>
// Must have a value
const version = '1.0.0';
// Cannot be reassigned
/ / version = '1.0.1';
// Constant values are object types
const user = {
name: 'Ming'.age: 18
}
// Cannot be reassigned
user = {};
Properties and methods can be modified
user.name = 'Xiao Xiao Ming';
user.gender = 'male';
</script>
Copy the code
Conclusion:
let
Declared variables have block scope,var
No block scope is generatedconst
Declared constants also generate block scope- Variables between different code blocks are not accessible to each other
- It is recommended to use
let
或const
Note: Let and const are often used indiscriminately in development. You can only declare const as a constant if you are worried that a value will change in no small way.
-
The keyword Block-level scope Variable ascension The initial value Change the value Call through window let Square root X) – Yes No const Square root X) Yes No No var x Square root – Yes Yes
1.2 Global scope
The outer layer of
- A variable is defined outside a function and is a global variable.
- Global variables have global scope: all scripts and functions in the web page can be used.
- If a variable is not declared in a function (without the var keyword), it is a global variable.
<script>
// This is global
function sayHi() {
// Here is a part
}
// This is global
</script>
Copy the code
Variables declared in a global scope can be accessed from any other scope, as shown in the following code:
<script>
// Global variable name
let name = 'Ming';
// function scope access global
function sayHi() {
// Here is a part
console.log('hello' + name);
}
// Global variables flag and x
let flag = true;
let x = 10;
// block scope accesses global
if(flag) {
let y = 5;
console.log(x + y); // x is global
}
</script>
Copy the code
Conclusion:
- for
window
Object dynamically added properties are also global by default, not recommended! - Function variables declared without any keywords are global variables, not recommended!!
- Declare as few global variables as possible to prevent global variables from being contaminated
Scope in JavaScript is the underlying mechanism by which programs are executed. Understanding this mechanism can help standardize code writing habits and avoid scope-related syntax errors.
1.3 Scope chain
Normally, a variable takes a value in the scope of the function that created it.
But if no value is found in the current scope, the chain is called the scope chain.
Before explaining what a scope chain is, let’s look at this code:
<script>
// Global scope
let a = 1;
let b = 2;
// local scope
function f() {
let c;
// local scope
function g() {
let d = 'yo'; }}</script>
Copy the code
New functions can be created inside a function. A new function g created inside f creates a new function scope.
As shown in the figure below, the scopes of the parent-child relationship are linked together to form a chain-like structure, hence the name of the scope chain.
The scope chain is essentially the underlying variable lookup mechanism. When a function is executed, it will first search the current function scope to find the variable. If the current function cannot find the variable, it will search the parent scope step by step until the global scope, as shown in the following code:
<script>
// Global scope
let a = 1;
let b = 2;
// local scope
function f() {
let c;
// let a = 10;
console.log(a); / / 1 or 10
console.log(d); / / an error
// local scope
function g() {
let d = 'yo';
// let b = 20;
console.log(b); / / 2 or 20
}
// call g
g()
}
console.log(c); / / an error
console.log(d); / / an error
f();
</script>
Copy the code
Conclusion:
- The scopes of nested relationships are concatenated to form scope chains
- Find variables in the same scope chain from smallest to largest
- Child scopes can access parent scopes, but parent scopes cannot access child scopes (proximity principle)
1.4 the closure
Closures are a special type of function that allows you to access variables in the function’s scope. A closure is a function that returns a value, as shown in the following code:
<script>
function foo() {
let i = 0;
// Some functions inside the function
function bar() {
console.log(++i);
}
// use the function as the return value
return bar;
}
// fn is the closure function
let fn = foo();
fn(); / / 1
</script>
Copy the code
/ / closures
function fn(){
let num = 124;
return function cn(){
console.log(num);
}
// cn();
}
let ra=fn();
ra();
ra();
ra();
Copy the code
Conclusion:
Closures: One scope has access to local variables of another scope,
Function: You can extend the scope of a variable
- Closures are still functions in nature, only they are not returned from inside functions
- Closures can create externally accessible isolation scopes, avoiding global variable contamination
- Overuse of closures can cause memory leaks
Note: Callback functions can also access local variables inside functions.
1.5 Variable promotion
Variable promotion is a “weird” phenomenon in JavaScript that allows variables to be accessed before they are declared,
<script>
// Access the variable STR
console.log(str + 'world! ');
// Declare the variable STR
var str = 'hello ';
</script>
Copy the code
Conclusion:
- Variables report syntax errors when accessed undeclared
- A variable is accessed before it is declared, and its value is
undefined
let
The declared variable does not have variable promotion and is recommendedlet
Some people think it has promotion but cannot be used without assignment.- Variable promotions occur in the same scope
- In practice, it is recommended to declare variables before accessing them
Note: The analysis of the principle of variable promotion will involve relatively complex lexical analysis and other knowledge, while the use of LET in the development can easily avoid the variable promotion. Therefore, we will not do too much discussion here, and you can refer to the information if you are interested.
Second, the function
Know the default value of function parameters, dynamic parameters, details of the use of residual parameters, improve the flexibility of function application, know the syntax of arrow function and the difference with ordinary functions.
2.1 Function promotion
Function promotion is similar to variable promotion in that a function can be called before it is declared.
<script>
// Call the function
foo();
// Declare the function
function foo() {
console.log('before the declaration is called... ');
}
// There is no promotion
bar();
var bar = function () {
console.log('Function expressions do not improve... ');
}
</script>
Copy the code
Conclusion:
- Function promotion allows for more flexibility in declaring calls to functions
- There is no promotion in function expressions
- Function promotion occurs in the same scope
2.2 parameter
The details of function parameters can improve the flexibility of function application.
The default value
<script>
// Set parameters to default values
function sayHi(name="Xiao Ming", age=18) {
document.write('<p> Hello everyone, my name is${name}This year, I${age}Years old. </p>`);
}
// Call the function
sayHi();
sayHi('little red');
sayHi('xiao gang'.21);
</script>
Copy the code
Conclusion:
- When declaring a function, assigning values to parameters is the default value of the parameters
- If no default value is defined for a parameter, the default value is
undefined
- When a function is called without an argument, the default value of the argument is passed as an argument
The dynamic parameters
Arguments is a pseudo-array variable built into a function that contains all the arguments passed in when the function is called.
<script>
// calculate the sum of all parameters
function sum() {
// console.log(arguments);
let s = 0;
for(let i = 0; i < arguments.length; i++) {
s += arguments[i];
}
console.log(s);
}
// Call the summation function
sum(5.10); // Two parameters
sum(1.2.4); // Two parameters
</script>
Copy the code
Conclusion:
arguments
It’s a pseudo-arrayarguments
Gets the argument to a function dynamically
The remaining parameters
<script>
function config(baseURL, ... other) {
console.log(baseURL);
// other is a true array that takes arguments dynamically
console.log(other);
}
// Call the function
config('http://baidu.com'.'get'.'json');
</script>
Copy the code
function fn(a,... e){
console.log(a,e);
}
fn(1.2.3.4.5)
Copy the code
Conclusion:
.
Is a syntax symbol that precedes the last function parameter and is used to get extra arguments- With the help of
.
Remaining arguments to get
2.3 Arrow Function
Arrow function is a concise syntax for declaring functions. It has no essential difference from ordinary functions. The difference lies in the syntax format.
<script>
// Arrow function
let foo = () = > {
console.log('^_^ odd-looking function... ');
}
// Call the function
foo();
// More concise syntax
let form = document.querySelector('form');
form.addEventListener('click'.ev= > ev.preventDefault());
</script>
Copy the code
Before the arrow function, each new function defined the function’s this value in terms of how it was called:
- If the function is a constructor, the this pointer points to a new object
- In strict mode function calls, this refers to undefined
- If the function is a method of an object, its this pointer points to that object
- , etc.
Conclusion:
- Arrow functions are expression functions, so there is no function promotion
- Arrow functions with only one argument can omit the parentheses
(a)
- Arrow functions can omit curly braces when the function body has only one line of code
{}
And is automatically returned as a return value - It’s not in the arrow function
arguments
, can only be used.
Get arguments dynamically - When it comes to the use of this, the arrow function is not recommended
3. Deconstruct assignment
Know the syntax and classification of deconstruction, use deconstruction concise syntax to quickly assign values to variables.
Deconstruction assignment is a concise syntax for quickly assigning values to variables. Essentially, it is still assigning values to variables. It can be divided into two types: array deconstruction and object deconstruction.
3.1 Array Deconstruction
Array deconstruction is a concise syntax for quickly batch assigning the unit values of an array to a series of variables, as shown in the following code:
<script>
// A normal array
let arr = [1.2.3];
// declare variables a, b, and c in batches
// Assign elements 1, 2, and 3 to variables A, B, and c
let [a, b, c] = arr;
console.log(a); / / 1
console.log(b); / / 2
console.log(c); / / 3
</script>
Copy the code
Conclusion:
- The assignment operator
=
On the left side of the[]
Used to declare variables in batches, the unit values of the right array will be assigned to the variable on the left - The order of the variables corresponds to the position of the array unit values
- When the number of variables is greater than the number of unit values, the extra variables will be assigned the value
undefined
- If the number of variables is less than the number of unit values, it can pass
.
Gets the remaining cell values, but only in the last digit - Default values for variables are allowed to be initialized, and only cell values are
undefined
The default value takes effect only when
Note: multi-dimensional deconstruction assignment is supported, which is more complex and can be further analyzed if there are application requirements
3.2 Object Deconstruction
Object deconstruction is a concise syntax for assigning object properties and methods to a series of variables in quick batches, as shown in the following code:
<script>
// Common objects
let user = {
name: 'Ming'.age: 18
};
// Batch declare variable name age
// Assign elements 1, 2, and 3 to variables A, B, and c
let {name, age} = user;
console.log(name); / / xiao Ming
console.log(age); / / 18
</script>
Copy the code
Conclusion:
- The assignment operator
=
On the left side of the{}
Used to declare variables in batches, property values of objects on the right will be assigned to variables on the left - The value of an object property will be assigned to a variable with the same name as the property
- Object could not find a property with a time varying value equal to the variable name
undefined
- Allows to initialize the default value of a variable, property non-existent or unit value
undefined
The default value takes effect only when
Note: multi-dimensional deconstruction assignment is supported, which is more complex and can be further analyzed if there are application requirements