当前位置:网站首页>ES6 new features (getting started)
ES6 new features (getting started)
2022-07-27 06:48:00 【Rice*】
One 、let and const command
JavaScript It is the language name we all know , What I learned today is ECMAScript 6.0( hereinafter referred to as ES6) yes JavaScript Language The next generation of standards . Its goal , Is making JavaScript Language can be used to write complex large applications , Become an enterprise development language .
that ,ECMAScript and JavaScript What is the relationship ? ECMAScript and JavaScript The relationship is , The former is the latter Specifications , The latter is an implementation of the former . Everyday occasions , These two words are interchangeable . among ES6 yes ECMAScript A standard of ,2015 Year by year ECMAScript The standards committee is in 2015 year 6 Officially released in , And from ES6 Start , Release a version every year , The version number is more than the year The last one is big 1.
Why should we study ES6?
- ES6 The version change content of is the most , It's a milestone ;
- ES6 Add many new syntax features , Programming is simpler 、 Efficient ;
- ES6 Is the front-end development trend , Necessary skills for employment .
1、let Basic usage of commands
let The keyword is used to declare variables , Function and var similar , But the use of let Declared variables have several characteristics
- Duplicate statements are not allowed .
- Block level scope .
- No variable promotion .
characteristic 1: Duplicate declaration of variables... Is not allowed
Mission 1: Use let Declare variables , Observation and var The difference between declaring variables .
<script type="text/javascript"> var a = 1; var a = 2; // Don't complain , The result is :2 console.log(a); //let Declared variables cannot be declared repeatedly let b = 3; let b = 4; // Console error , Error message :Uncaught SyntaxError: Identifier 'b' has already been declared console.log(b); </script>Results show , Variable b Already declared , Cannot declare more than once .
var It can be stated many times ,let It can only be declared once .
characteristic 2: Block level scope
let Declared variables have strict local scope , Can only be used in block level scope
Mission 2: Observe the effect of block level scope
<script type="text/javascript"> { var a = 1; let b = 2; } // The result is :1 console.log(a); // Report errors console.log(b); </script>result :

From the example above , It can be concluded that :var Declared variables can be operated globally , and let Although the usage of declared variables is similar to var, however Declared variables , Only in let The command is valid in the code block . Include if、else、while、for Use let Can only be in the code fast It works .
for example :for Cycle counter , It is suitable for use let command .
<script type="text/javascript"> for (var i = 0; i<=10; i++) { } // The result is :11 console.log(i); for (let x = 0; x<=10; x++) { } // Report errors console.log(x); </script>result :

Counter i Only in for Circulating efficiency , It will report an error if it is quoted outside the circulation .
characteristic 3: No variable promotion
var The command will happen " Variable Promotion " The phenomenon , That is, variables can be used before they are declared , The value is undefined. Thinking according to programming logic , Variable You should only use after the declaration statement .
In order to correct this phenomenon ,let Command changes the grammatical behavior , The variables it declares must be used after declaration , Otherwise, the report will be wrong .
Examples are as follows :
<script type="text/javascript"> // No variables defined a It's a mistake :Uncaught ReferenceError: a is not defined // Defining variables a in the future , Print undefined. console.log(a); var a = 1; // Whether variables are defined or not b, All will report wrong. :Uncaught ReferenceError: b is not defined console.log(b); let b = 2; </script>
about let Characteristics of , That's all , Of course let There are many other features , For example, temporary deadband 、 It does not affect the scope chain , As you can Go on and teach yourself . All in all , In the future, declare variables and use more let That's right .
2、const Basic usage of commands
const Keyword is used to declare a read-only constant , Once declared , The address of a constant cannot be changed . What is a constant ? A constant is a value ( Memory address ) An unchangeable quantity .const The statement has the following characteristics :
- Block level scope
- Identifiers are usually uppercase ( standard )
- The declaration must be assigned an initial value
- Value cannot be modified
- Duplicate statements are not allowed
characteristic 1: Block level scope
Sample code ;
<script type="text/javascript"> { const a = 1; } // Report errors :Uncaught ReferenceError: a is not defined console.log(a); </script>Mission 3: After running the following code , What is the result of three lines of code .
<script type="text/javascript"> { const A = 1; { const A = 2; // Print first , result :2 console.log(A); } // Post print , result :1 console.log(A); } // Report errors :Uncaught ReferenceError: A is not defined console.log(A); </script>result :

characteristic 2: The address cannot be modified
Sample code
<script type="text/javascript"> const a = 1; // Report errors :Uncaught SyntaxError: Identifier 'a' has already been declared const a =2; </script>result :

The above code indicates that changing the value of a constant will result in an error ,const Declared variable must not change value . It means ,const Once a variable is declared , It will Must be initialized immediately , It cannot be left for later assignment .
characteristic 3: The declaration must be initial
Sample code
<script type="text/javascript"> // Report errors :Uncaught SyntaxError: Missing initializer in const declaration const a; </script>result :

const The essence :
const It is not actually guaranteed that the value of the variable cannot be changed , But the memory address that the variable points to must not be changed . For numbers of simple types According to the ( The number 、 character string 、 Boolean value ), The value is stored at the memory address that the variable points to , So it's equivalent to a constant . But for data of composite type ( Mainly objects and arrays ), The memory address that the variable points to , It's just a pointer ,const It can only be guaranteed that the pointer is fixed , as for Whether the data structure it points to is variable , It's totally out of control .
therefore , You must be very careful when declaring an object or array as a constant .
Mission 4: Use const Declare constant objects , Observe the mutability and immutability of constant objects .
<script type="text/javascript"> const stu = { name:" Zhang San ", age:20 } // result :{name: " Li Si ", age: 20} console.log(stu); stu.name = " Li Si "; // result :{name: " Li Si ", age: 20} console.log(stu); // Report errors :es6.html:21 Uncaught TypeError: Assignment to constant variable. stu = { }; </script>result :

In the above code , Constant obj It stores an address , This address points to an object . What is immutable is the address specified by the object , also Just can't put foo Point to another address , But the object itself is variable , You can add a new attribute or modify the value of the attribute .
Mission 5: Use const Declare constant objects , Observe the mutability and immutability of constant arrays .
<script type="text/javascript">
const TV = [" Bear haunt "," Pleasant goat and grey wolf "," Pig man "];
TV.push(" Shock boy "); // Executable
TV.length = 0; // Executable
// Report errors :Uncaught TypeError: Assignment to constant variable.
TV = [" Peppa Pig "];
</script>
In the above code , Constant TVS Is an array , The array itself is readable, writable, and operable , But if you assign a value to another array to TVS, You're going to report a mistake .
3、let、const and var Distinction of command
- Use var Declared variables , Its scope is within the function of the statement , And there is the phenomenon of variable promotion .
- Use let Declared variables , Its scope is in the code block where the statement is located , No variable promotion .
- Use const Declared constant , You can't change the value of this constant in later code .

Two 、 Deconstruction and assignment of variables
ES6 Allow to follow certain mode , Extract values from arrays and objects , Assign values to variables , This is called deconstruction assignment . It can help us to be simpler Extract values from arrays and objects .
1、 Array deconstruction assignment
- Before , To assign a value to a variable from an array , You can only specify values directly .
<script type="text/javascript">
const arr = [1,2,3]
let a = arr[0];
let b = arr[1];
let c = arr[2];
</script>
- Now? ES6 Allow to write as follows :
<script type="text/javascript">
const arr = [1,2,3]
let [a,b,c] = arr;
console.log(a);
console.log(b);
console.log(c);
</script>
The code above indicates , You can extract values from arrays , According to the corresponding position , Assign a value to a variable . Essentially , This is the way it's written “ Pattern matching ”, As long as the patterns on both sides of the equal sign are the same , The variable on the left is given the corresponding value . In Deconstruction , There are two parts to participate in :
- The source of deconstruction , Deconstruct the right part of the assignment expression .
- The goal of deconstruction , Deconstruct the left part of the assignment expression .
When the target of the deconstruction is the same as the source of the deconstruction , You can assign the data in the source to the variable . It should be noted that : Deconstruction and of arrays It's about order , The adjustment of the order will change the value of the variable .
In the deconstruction of array model , There are also the following operations , You can get to know :
// Basic operation let [a, b, c] = [1, 2, 3]; // result :a = 1 b = 2 c = 3 // Nested operations let [a, [[b], c]] = [1, [[2], 3]]; // result :a = 1 b = 2 c = 3 // Operation can be ignored let [a, , b] = [1, 2, 3]; // result :a = 1 b = 3 // Remainder operator let [a, ...b] = [1, 2, 3]; // result :a = 1,b = [2, 3] // Incomplete deconstruction let [a = 1, b] = []; // result :a = 1, b = undefined let [x, y, z] = [1, 2]; // result :x = 1, yIt should be noted here that if the deconstruction is not successful , Variables are not assigned , The value is equal to undefined.
2、 Object deconstruction assignment
An important difference between object deconstruction and array . The elements of an array are Arranged in order , The value of a variable depends on its position ; And the object's Attributes have no order , Variable must have the same name as property , To get the right value . Object deconstruction allows us to use The name of the variable matching Object properties , Assign the attribute of the object to the variable .
Mission 3-1: Use deconstruction assignment to manipulate objects , Observe what happens if attributes and variables are inconsistent .
<script type="text/javascript"> const STU = { name:" Zhang San ", age:20 }; let { name,age} = STU; // Zhang San console.log(name); //20 console.log(age); </script>Example of the above code , The order of the two variables to the left of the equal sign , The order of the two attributes with the same name to the right of the equal sign is inconsistent , But the value is not at all Have an impact on . Instead, the last line of code , Because the variable name has no corresponding attribute with the same name , Resulting in a loss of value , The resulting variable value is undefined.
If the variable name is not the same as the property name , It must be written as follows :
<script type="text/javascript">
const STU = {
name:" Zhang San ",
age:20
};
let {
name: name2,age: age2} = STU;
// Zhang San
console.log(name2);
//20
console.log(age2);
</script>
3、 Special deconstruction assignment
3.1、 String deconstruction assignment
Strings can also deconstruct assignments . And that's because right now , The string is converted to an array like object . String deconstruction is similar to array deconstruction , You can assign characters to variables in order .
<script type="text/javascript">
const str = "hello!";
let [a,b,c,d,e,f] = str;
//h
console.log(a);
//e
console.log(b);
//l
console.log(c);
//l
console.log(d);
//o
console.log(e);
//!
console.log(f);
</script>
The objects of class array have a length attribute , Therefore, you can also assign a value to the deconstruction value of this attribute .
<script type="text/javascript"> const str = "hello!"; let { length: len} = str; //6 console.log(len); </script>
3.2、 Function parameter deconstruction assignment
Deconstruction assignment can also be used for parameter functions in our commonly used functions , Formal parameters can be reused arrays 、 object 、 String and other ways of deconstruction , Will pass on The input parameters are parsed and assigned to variables .
Examples are as follows :
function add([a, b]){ // Assign the value of the passed in array to a and b Variable return a + b; } add([1, 2]); // result :3When object methods are used frequently 、 Array elements , You can use the deconstruction assignment form . For deconstruction assignment, let's stop here for the moment , There are also many in Deconstruction Many usages need to be explored .
3、 ... and 、 String extension
1、 Template string
Declare a string before , Single quotation mark ’' And double quotes "" Two ways of writing ,ES6 Introduced template string ``. Template string (template string) It's an enhanced string , Use back quotes (`) identification .
characteristic :
A newline character can appear in the string ;
have access to ${xxx} As placeholder , Form output variables or expressions in braces ;
Mission 4: Use quotation marks and template strings to change
// Use double quotation marks to wrap let comedy1 = "<ul>" + "<li> Shen Tang </li>" + "<li> Ma Li </li>" + "<li> Allen </li>" +"</ul>"; // Use template string to realize line feed let comedy2 = `<ul> <li> Shen Tang </li> <li> Ma Li </li> <li> Allen </li> </ul>`; According to the example effect, we can find , The string written by the template string does not have the problem that the code cannot run because of line feed , And it's very convenient to use .
Mission 5: Use ${xxx} Complete variable output .
let wl = " Zhuang Qiang ";
let fc = " Great intelligence ";
let str = ` wolong ${
wl} And chicks ${
fc}, One can get the world !!!`;
// result : Wolong Zhuang strong chicks are smart , One can get the world !!!
console.log(str);
Be careful :${} It's fixed writing , Don't make a mistake !!!
2、 String extension function
Traditionally ,JavaScript Only indexOf Method , Can be used to determine if a string is contained in another string .ES6 Also provide Three new methods .
includes(): Returns a Boolean value , Indicates whether the parameter string was found .
startsWith(): Returns a Boolean value , Indicates whether the parameter string is in the header of the source string .
endsWith(): Returns a Boolean value , Indicates whether the parameter string is at the end of the source string .
Mission 6: Use string extension function , And observe the results .
<script type="text/javascript"> let f4 = ` The northeast F4: leonardo · Little Shenyang 、 Johnny · Song Xiaobao 、 Christian · Liu Neng and Nicholas · Zhao si !!!`; // Judge whether " The northeast " start console.log(f4.startsWith(" The northeast "))//true // Judge whether " Four " ending console.log(f4.endsWith(" Four "))//false // Judge whether it includes " Nicholas " console.log(f4.includes(" Nicholas "))//true </script>All three methods support the second parameter n, Indicates where to start the search ,n from 0 Start . But use the second parameter n when ,endsWith Our behavior is different from the other two methods . It's for the front n Characters , And the other two methods are from n Positions until the end of the string .
Mission 7: Observe the string expansion function , Add a second parameter n, And observe the results .
<script type="text/javascript">
let f4 = ` The northeast F4: leonardo · Little Shenyang 、 Johnny · Song Xiaobao 、 Christian · Liu Neng and Nicholas · Zhao si !!!`;
// The indexes are all from 0 At the beginning !!!
// Judge from the fourth index , Whether it starts with "true"
console.log(f4.startsWith(":",4))//true
// Before judgment 4 Whether characters begin with 4 ending
console.log(f4.endsWith("4",4))//true
// Judge from 9 Start , Does it include " Small " word
console.log(f4.includes(" Small ",9))//true
// Judge from 20 Start , Does it include " Small " word
console.log(f4.includes(" Small ",20))//false
</script>
Four 、 Function and object optimization
1、 Function optimization
1.1、 Function parameter defaults
- stay ES6 before , We can't set the default value for a function parameter , You can only use alternative writing :
<script type="text/javascript">
function add(a,b){
b = b || 1
return a+b;
}
//3
console.log(add(2))
</script>
stay ES New features , You're allowed to write that : Write the default value directly to the parameter , If not, the default value will be used automatically
<script type="text/javascript"> function add(a,b=1){ return a+b; } //3 console.log(add(2)) </script>The advantage of doing so is , First of all, for those who read the code , You can immediately realize which parameters can be omitted , Don't check the function body or text files ; secondly , Conducive to future code optimization , Even if the future version is in the external interface , Completely remove this parameter , Nor will it lead to previous code Unable to run .
It should be noted that :
- When using function default parameters , Parameters with the same name are not allowed .
- Only if the parameter is not passed , Or the parameter is undefined when , Will use the default parameters ,null Values are considered valid value passing .
5、 ... and 、 Extension operator (…)
1、 Function parameter
rest Parameters are also called indefinite parameters , Used to express the number of uncertain parameters . Grammar is :... Variable name . from ... Plus a named parameter identifier .
Basic usage : Function name (… Indefinite parameter name ).
Examples are as follows :
<script type="text/javascript"> function fn(...vals){ console.log(vals); console.log(" length :" + vals.length); } // result :(3) [1, 2, 3] length :3 fn(1,2,3); // result :(6) [1, 2, 3, 5, 4, 3] length :6 fn(1,2,3,5,4,3); </script>Through the above operation, we found ,rest The indefinite parameter is an array , Here you can use some of the array Api, for example some、map Methods or length Properties, etc , It improves the flexibility of parameter processing . But here's the thing Indefinite parameters can only be placed at the end of the parameter group , And a function has only one indefinite parameter .
2、 The output array
Extension operator (spread) Three points (…). It's like rest Inverse operation of parameter , Convert an array into comma separated parameters Sequence .
Before , If you need to output the value of an array , It needs to be done :
<script type="text/javascript"> let arr = [1,2,3]; // result :1 2 3 console.log(arr[0] + " " + arr[1] + " " + arr[2]); </script>Now there is the extension operator , You can write like this :
<script type="text/javascript"> let arr = [1,2,3]; // result :1 2 3 console.log(...arr); </script>
3、 Merge array
Mission 1: Use the expansion operator to merge arrays .
<script type="text/javascript"> let arr = [1,2,3]; let arr2 = [4,5,6]; // Old style result :(6) [1, 2, 3, 4, 5, 6] console.log(arr.concat(arr2)); // neographism result :(6) [1, 2, 3, 4, 5, 6] console.log([...arr,...arr2]); </script>You can write like this :
<script type="text/javascript"> let arr = [1,2,3]; let arr2 = [4,5,6]; arr.push(...arr2); // result :(6) [1, 2, 3, 4, 5, 6] console.log(arr); </script>
4、 Clone array
Mission 2: Use the extension operator to clone the array .
<script type="text/javascript"> let arr = [1,2,3]; let arr2 = [...arr]; // result :(3) [1, 2, 3] console.log(arr2); </script>
5、 Convert pseudo array to array
- Mission 3: Using the extension operator will div Pseudo array to array .
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<script type="text/javascript"> let divs = document.getElementsByTagName("div"); // result :HTMLCollection(3) [div, div, div] console.log(divs); let divarr = [...divs]; // result :(3) [div, div, div] console.log(divarr); </script>
</body>
6、 Copy the object
- Mission 4: Use the extension operator to complete the object copy .
<script type="text/javascript">
let stu = {
name:" Zhang San ",
age:20
}
let stus = {
...stu};
// result :{name: " Zhang San ", age: 20}
console.log(stus);
</script>
The copy in the example is actually a deep copy , Interested students can learn about deep and shallow copies .
- Shallow copy (shallowCopy) It just adds a pointer to an existing memory address .
- Deep copy (deepCopy) A pointer is added and a new memory is requested , Make the added pointer point to the new memory .
6、 Object value consolidation
Mission 5: Use the extension operator to complete the operation of object merging .
<script type="text/javascript"> let st1 = { name:" Zhang San ",age:20}; let st2 = { age:21}; let st3 = { sex:" male "}; st3 = { ...st1,...st2,...st3}; // result :{name: " Zhang San ", age: 21, sex: " male "} console.log(st3); </script>
6、 ... and 、 Arrow function
ES6 Allow to use 「 arrow 」(=>) Defined function , Provides a more concise way to write functions . The basic grammar is : Parameters => function
Previously, we declared that a function is written like this :
<script type="text/javascript"> console.log("-----------------------1 Parameter function ----------------------------") let fun1 = function(val){ return val; } console.log(fun1(1)); </script>ES6 How to write it :
<script type="text/javascript"> let fun1 = val => val; </script>
Be careful 1: If there is only one function parameter , It can be omitted (), In addition, parentheses cannot be omitted whether there are no parameters or multiple parameters ().
Examples are as follows :
<script type="text/javascript"> console.log("-----------------------1 Parameter function ----------------------------"); // Common writing let fun1 = function(val){ return val; } console.log(fun1(1)); // Arrow writing let fun2 = val => val; console.log(fun2(2)); console.log("----------------------- Nonparametric functions ----------------------------"); // Common writing let fun3 = function(){ console.log("3"); } fun3(); // Arrow writing let fun4 = () => console.log("4"); fun4(); console.log("----------------------- Multiparametric functions ----------------------------"); // Common writing let fun5 = function(a,b){ return a+b; } console.log(fun5(2,3)); // Arrow function let fun6 = (a,b) => a+b; console.log(fun6(3,3)); </script>result :

Be careful 2: When an arrow function body has multiple lines , use {} Curly braces , Wrap it up , Represents a code block . When there is only one line , It can be omitted {} Curly braces . When There is only one line and it is return When returning results , It can be omitted {} and return, The return value will be returned automatically .
Examples are as follows :
<script type="text/javascript"> console.log("----------------------- Methods there are multiple lines in the body ----------------------------"); // Common writing let fun7 = function(a,b){ let sum = a+b; return sum; } console.log(fun7(3,4)); // Arrow function let fun8 = (a,b) => { let sum = a+b; return sum; } console.log(fun8(4,4)); console.log("----------------------- The method body is a single line ----------------------------"); // Common writing let fun9 = function(a,b){ return a+b; } console.log(fun9(4,5)); // Arrow function let fun10 = (a,b) => a+b; console.log(fun10(5,5)); </script>result :

Be careful 3: When the arrow function returns an object , To distinguish between code blocks , Use parentheses () Wrap objects .
Examples are as follows :
<script type="text/javascript"> console.log("----------------------- Method body is object ----------------------------"); // Common writing let fun11 = function(num1,num2){ return { num1:num1, num2:num2 } } console.log(fun11(5,6)); // Arrow function //let fun12 = (num1,num2) => {num1:num1,num2:num2};// Report errors let fun12 = (num1,num2) => ({ num1:num1,num2:num2});// correct console.log(fun12(6,6)); </script>result :

Be careful 4: Object assignment abbreviation
stay ES6 Before , Our assignment object needs to be written like this :
<script type="text/javascript"> console.log("---------------------ES6 Assignment of previous objects ----------------------------"); //ES6 Previous assignment var fun13 = function(num1,num2){ return { num1:num1, num2:num2 } } console.log(fun13(6,7)); //ES6 Previous arrow function assignment var fun14 = (num1,num2) => ({ num1:num1,num2:num2}); console.log(fun14(7,7)); </script>result :

ES6 in the future , Our assignment object only needs to be written like this :
<script type="text/javascript"> console.log("---------------------ES6 Then the assignment of the object ----------------------------"); //ES6 Then assign a value let fun15 = function(num1,num2){ return { num1, num2 } } console.log(fun15(7,8)); //ES^ Later, the arrow function is assigned let fun16 = (num1,num2) => ({ num1,num2}); console.log(fun16(8,8)); </script>result :

Note the arrow function :
- If there is only one parameter , Then brackets can be omitted .
- If there is only one statement in the function body , Then braces {} It can be omitted .
- If the function body has only one statement and is the return value , You can omit the braces {} and return.
- Arrow function this Always point to... Under the scope where the function is declared this Value , No window.
- Arrow functions cannot be instantiated as constructors .
- Out of commission arguments object .
Notice above , The fourth point is particularly noteworthy . Of a normal function this The direction of the object is variable , But in the arrow function , It's fixed Of . Arrow function this Is static ,this Always point to... Under the scope where the function is declared this Value .
7、 ... and 、 Method shorthand
ES6 Before , Define methods :
<script type="text/javascript"> var fun17 = { say: function(){ console.log(" Hello "); } } fun17.say(); </script>ES6 after , Define methods :
<script type="text/javascript"> let fun18 = { say(){ console.log(" Hello "); } } fun18.say(); </script>result :

8、 ... and 、module modular ( important )
1、 summary
In the history of ,JavaScript There has been no module (module) system , Cannot split a large program into interdependent small files , Then use simple Method to assemble . It's available in other languages , such as Ruby Of require、Python Of import, Even even CSS There are @import, however JavaScript There's no support for that , It's important to develop 、 Complex projects create huge obstacles . ES6 Introduce modules Module system , adopt export The code of the specified output displayed by the command , adopt import Command input the specified code . although JavaScript stay ES6 You can also use CommonJS and AMD There are two ways to realize module loading . however ES6 Static thinking of modules , send The dependencies of modules can be determined at compile time , And input and output variables , It is possible to use static analysis , Further broaden JavaScript The grammar of .
Simply speaking : Modularization is to put a large program file , Split into many small files , Just like Lego blocks , Then use through splicing , Combine small files .
The benefits of modularity :
- Prevent naming conflicts
- Code reuse
- High maintenance
ES6 Module function is mainly composed of two commands :export and import
- export Command is used to specify the external interface of the module .
- import Commands are used to enter functions provided by other modules .
2、 First experience of module commands
Before learning commands , We need to understand a concept . stay ES6 Module definition , A module is a separate file . Inside the file By variable 、 Method , No external access or operation . If you want to read a variable inside the module externally , We need to make use export Keywords expose the output ,import Keyword input .
Next use ES6 Module command , Experience the convenience of output and input modules , The specific operation is as follows :
New projects , In the project js Create file in file m1.js, route :./js/m1.js. stay js In file , Expose variables and functions , To write , The code is as follows :
export let sname = " Jack ma, "; export function say(){ console.log(" Hello everyone , My name is Ma Yun "); }
Be careful : The exposed exported syntax here is :export Variable | function .
New in the root directory test.html, route :/test.html, stay html In file , introduce m1.js modular , Write the code as follows :
<script type="module"> // The import module It's also called m1 import * as m1 from "./js/m1.js"; // The console prints the imported module console.log(m1); </script>result :

We found it through export and import Two commands , You can introduce the modular content of other files , It's very convenient to operate .
Be careful :
- The input syntax here is ;import * as Alias from route .
- script Labeled type The type is module.
- as names .
- from Module file location after , Can be a relative path , It could be an absolute path .
Summary :
export grammar
//export Variable declarations ; example : export let Variable name = value ; //export Function declaration ; example : export function Function name (){ // The body of the function }import grammar
<script type="module"> // Import all modules as Alias operation import * as Alias from " Location of module file "; </script>
3、export Expose orders
The way 1: Unified exposure
In the above study , We learned that we can expose the data content separately , In addition, the data can also be exposed uniformly .
The grammar is as follows :
// Unified exposure grammar export { Variable 1, Variable 2, Function name 1, Function name 2};// Here is only the function name , Without bracketsnewly build m2.js, The code example is as follows :
let sname = " ma "; function say(){ console.log(" Hello everyone , My name is Ma Huateng "); } // Single exposure method /* export {sname}; export {say}; */ // Uniform exposure method //export {sname,say}; // Use as Keywords are aliased export { sname as a, say as b};Test introduction , The code is as follows :
<script type="module"> // The import module It's also called m2 import * as m2 from "./js/m2.js"; // The console prints the imported module console.log(m2); </script>Three test results :

** Be careful :** Here's the thing to watch out for ,export The order specifies an external interface , One to one correspondence must be established with the variables inside the module . The following is an example of an error :
// Report errors , You cannot export values directly
export 1;
// Report errors , We should add {}, Be right :export {num}
let num = 1;
export num;
// Report errors , Like the second mistake , No addition {}
function fn(){
};
exoport fn;
The way 2: Default exposure
establish m3.js file , Examples are as follows :
// How to write it 1 /* let sname = " Lei jun "; function say(){ return " Hello everyone , My name is Lei Jun "; } export default {sname,say}; */ // How to write it 2 export default { sname:" Lei general ", say(){ return " Hello everyone , I'm Mr. Lei "; } }The test import is as follows :
<script type="module"> // The import module It's also called m3 import m3 from "./js/m3.js"; // The console prints the imported module console.log(m3); </script>The results of the two methods are as follows :

Be careful :
- In each module , Only one use is allowed export defulat Default exposure command .
- Default defulat It is a layer more than ordinary exposure default.
4、import Import command
Use export After the command defines the external interface of the module , other JS The file can be passed import Command to load this module . Let's learn from Use the asterisk (*) Introduce the contents exposed by the whole module , Next, let's learn about on-demand introduction .
The way 1: Introduce on demand
You can use the form of deconstruction assignment , adopt import The command implements the on-demand introduction of modules ( Import ).
The grammar is as follows :
import { Variable 1, Variable 2, function 1, function 2} from " Location of module file ";The code example is as follows :
//m1.js Content export let sname = " Jack ma, "; export function say(){ console.log(" Hello everyone , I'm Ma Yun "); } // New page test_import.html Page import code <script type="module"> import { sname,say} from "./js/m1.js; console.log(sname); // Output results : Jack ma, </script>
By the above operation , We can introduce variables or functions as needed , Just need a brace , You can get the content in the specified module , The writing method is very similar to the previous deconstruction assignment operation .
Let's test it , Simultaneous introduction m1.js and m2.js. The code example is as follows :
// New page test_import.html The page introduce m1 and m2 Code <script type="module"> import { sname,say} from "./js/m1.js; import { sname,say} from "./js/m2.js; console.log(sname); </script>The results are as follows :

The error is reported here because of the imported variable sname repeated , We can use as Keyword to rename variables or functions , As shown below :
// New page test_import.html The page introduce m1 and m2 Code <script type="module"> import { sname,say} from "./js/m1.js"; import { sname as a ,say as b} from "./js/m2.js"; console.log(sname); console.log(a); </script>result :

The way 2: Introduction method for default exposure
The grammar is as follows :
import Alias from " Location of module file "; import { default as Alias } from " Location of module file ";The code example is as follows :
// New page test_import.html The page introduce m3.js <script type="module"> import aa from './js/m3.js'; import { default as bb} from './js/m3.js'; console.log(aa.sname); console.log(bb.sname); </script>result :

Essentially ,export default Is to output a called default Variable or method of , Then the system allows you to give it any name .
The way 3: Multiple combinations of default exposure and normal exposure
When there are default and normal introductions , The grammar is as follows :
import Default alias ,{ General introduction } from " Location of module file ";- Need to pay attention to when , The default import must be in front of the normal import .
newly build m4.js file , The code is as follows :
let name1 = " Imperial commander . Liu Guoliang "; let name2 = " Fat people who don't know the ball . Liu Guoliang "; export default { name1}; export { name2};newly build test_improt2.html, The code is as follows :
<script type="module"> import df,{ name2} from "./js/m4.js"; console.log("name1-->" + df.name1); console.log("name2-->" + name2); </script>result :

Nine 、js Medium this keyword ( Expand )
this Keywords can be divided into three situations :
Ordinary function : Who is calling , Point to the who .
Arrow function : Point to the parent class of the caller .
Anonymous functions fall into two categories :
- Normal anonymous function : Never point to window object .
- Arrow anonymous function : Point to the parent class of the caller
Examples are as follows :
<script type="text/javascript"> console.log("------------------ Case one : Who is calling ,this Just point to who -------------------"); // test 1: Print the results :window object console.log(this); // test 2 let fun1 = function(){ console.log(this); } /* Print the results :whindow object , * Because when implementing the method , Default window.fun(), * window It can be omitted , When called, it is window Object called . */ fun1(); console.log("----------- The second case : Arrow function ,this Point to the caller's parent --------------"); // test 1( For comparison ), Ordinary function , the reason being that obj Method called , therefore this Point to obj let obj = { name: " Zhang San ", say: function(){ console.log(this); } } // The result is :obj object obj.say(); // test 2: Arrow function let obj2 = { name: " Zhang San 2", say: () => console.log(this) } // The result is :window object , because this The caller of is obj2,obj2 The father of window obj2.say(); console.log("----------- The third case : Anonymous functions ( There are two situations )--------------"); // Normal anonymous function : The functions in the timer are anonymous functions , Anonymous functions in ordinary functions always point to window object let obj3 = { name: " Zhang San 3", say: function(){ setTimeout(function(){ console.log(this); },100); } } // The result is :window object obj3.say(); // Arrow anonymous function : The functions in the timer are anonymous functions , The anonymous function in the arrow function points to the parent class of its caller let obj4 = { name: " Zhang San 3", say: function() { setTimeout(() => { console.log(this); },100); } } // The result is :obj4 object Because there are arrow anonymous functions in the timer , Point to the caller (say) Parent class of (obj4) obj4.say(); </script>result :

边栏推荐
- shell的编程规范and重定向与管道操作
- LAMP--源码编译安装
- DHCP principle and configuration
- 如何避免漏洞?向日葵远程为你讲解不同场景下的安全使用方法
- shell--条件语句(if语句、case语句)
- Basic knowledge of English: Rules for the use of non predicates Part 1
- ESXI虚拟机启动,模块“MonitorLoop”打开电源失败
- NFS introduction and configuration
- Explanation of server related indicators
- Packaging of logging logs
猜你喜欢

NFS简介和配置

Publish a building segmentation database with a resolution of 0.22m

LVM与磁盘配额

win10 添加虚拟网卡,配置op路由

Iptables firewall, SNAT and DNAT

logging日志的封装

Sunflower: don't worry when you encounter computer vulnerabilities, understand clearly and then judge sunflower: don't worry when you encounter computer vulnerabilities, understand clearly and then ju

改善宝宝过敏就吃伊敏舒,azg与Aibeca爱楽倍佳携手守护中国宝宝成长

众多世界500强企业集聚第二届数博会,数字产业大幕即将开启!

账号管理与权限
随机推荐
GoLand writes Go program
Soul持续发力社交渠道赴港上市,“Soul式社交”凭什么火出圈?
Many of the world's top 500 enterprises gathered at the second digital Expo, and the digital industry curtain is about to open!
To improve the baby's allergy, take yiminshu. Azg and aibeca love la Beijia work together to protect the growth of Chinese babies
FTX US推出FTX Stocks,向主流金融行业迈进
Go language learning
1. CentOS 7 安装 redis
How to write yaml file in a standard way
KVM command set management virtual machine
darknet-yolov3、yolo-fastect使用rtx30系显卡cuda环境在win10平台编译与训练的相关问题
向日葵全面科普,为你的远程控制设备及时规避漏洞
Raid explanation and configuration
Shell sentence judgment exercise
云原生运行环境搭建
磁盘管理与文件系统
Shell语句判断练习题
Create a container that does not depend on any underlying image
Shell -- operation of variables
网站服务器被攻击怎么办?向日葵提示防范漏洞是关键
win10 添加虚拟网卡,配置op路由