当前位置:网站首页>Esmascript 6.0 advanced

Esmascript 6.0 advanced

2022-06-09 05:26:00 Classmate Tao Ran.

Catalog

1. Advanced Grammar

        1.1 Variable declarations

        1.2 Deconstruct assignment

       1.3 Function parameter name default

        1.4 Arrowhead function this

        1.5Map data structure (Map aggregate )

       1.6Set data structure (Set aggregate )

        1.7for...of Traverse

        1.8rest Parameters ( Shape parameter ...)

        1.9 Extension operator ( Actual parameters ...)

2. modularization

        2.1ES5 CommonJS Solution

        2.2ES6 module Implicit requirements

        2.3ES6 module

        2.4 The default is derived export default


1. Advanced Grammar

        1.1 Variable declarations

keyword

Whether there is

Variable Promotion

Whether there is

Temporary dead zone

Whether to allow

Repeat statement

Whether to allow

Reassign

Whether to allow

only Declaration does not assign value

var

There is

non-existent

allow

allow

allow

let

non-existent

There is

Don't allow

allow

allow

const

non-existent

There is

Don't allow

Don't allow

Don't allow

  • var
//1 var  Declared variables , Can improve 
{
    var a = 10;
}
console.info(a);    //10

//2  Allow duplicate statements 
var b = 20;
var b = 30;
console.info(b);   //30

//3  Allow reassignment 
b = 40;
console.info(b);   //40

//4  It is allowed to declare only non assignment 
var c;
console.info(c);    //undefined
  • let

//1 let Declared variables , Variable promotion not allowed 
/*
{
    let a = 10;
}
console.info(a);    // abnormal , a is not defined
*/

//2  There is a temporary dead zone  :  In block code , All variables are local variables  ( Must declare first , Reuse )
/*
var b = 10;
{
    console.info(b);        //b is not defined
    let b = 20;
}
*/

//3  Duplicate statements are not allowed 
/*
var c = 10;
let c = 20;     //Identifier 'c' has already been declared  ( Variable c It has been declared that )
*/

/**/
//4  Allow reassignment 
let d = 10;
d = 20;
console.info(d);    //20

//5  It is allowed to declare only non assignment 
let e;
console.info(e);    //undefined
  • const
const a = 10;

//1.  No lifting is allowed 
/*
{
    const b = 10;
}
console.info(b)     //b is not defined
*/

//2.  There is a temporary dead zone 
/*
var c = 10;
{
    console.info(c)     //c is not defined
    const c = 20;
}
*/

//3.  Duplicate statements are not allowed 
/*
const a = 20;           //Identifier 'a' has already been declared
*/

//4.  Reassignment is not allowed 
/*
a = 20;             //Assignment to constant variable.
*/

//5.  It is not allowed to declare only non assignment 
//const d;            // Missing initializer in const declaration

        1.2 Deconstruct assignment

  • ES6 Allow to follow certain mode , Extract values from arrays and objects , Assign values to variables , This is called deconstruction (Destructuring)
  • ES5 Syntax for getting object data , as follows :
const people = {
    name: 'lux',
    age: 20
}
const name = people.name;				//ES5 How to write it 
const age = people.age;
console.log(name + ' ‐‐‐ ' + age)
  • Object to deconstruct : Parse multiple attributes from an object to different variables at once
    • Deconstructed variable names , Must be consistent with property name .
var person = {
    username : "jack",
    password : "1234",
    "show" : function(){
        console.info("show Yes ");
    },
    course : {
        en : 100,
        math : 99
    }
}

//es5 Get data 
console.info( person.username )
console.info( person.password )
person.show()

// Object to deconstruct 
let {username,password,show, age } = person;
console.info(username)      //jack
console.info(password)      //1234
console.info( show )        //[Function: show]
console.info( age )         //undefined
show();                     //show Yes 

// Objects in structure objects 
let {course} = person;
console.info(course)    //{ en: 100, math: 99 }
let {course : {en, math}} = person;
console.info(en)        //100
  • An array of deconstruction : Assign values in order of array order
//  Declaration array 
var arr = [' jiangsu ',' Suqian '];

//  Deconstruct members from an array 
let [province, city] = arr;
console.info(province)
console.info(city)

// In exchange for 2 A variable 
let x = 10;
let y = 20;
console.info(`x = ${x} , y = ${y}`);
[y,x] = [x,y];
console.info(`x = ${x} , y = ${y}`);
  • Common applications : Traverse Map ( Explain later )
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world
  • Common applications : Module content extraction ( Explain later )
const { SourceMapConsumer, SourceNode } = require("source-map");

       1.3 Function parameter name default

  • When declaring function parameters , Set default values for parameters
function log(x, y = 'World') {				//y Parameter setting defaults 
    console.log(x, y);
}

log('Hello') 								// Hello World
log('Hello', 'China') 						// Hello China
log('Hello', '') 							// Hello
  • Default and deconstruction
function fun1({x = "x1" , y } = {y : "y2"}){
    return [x , y] ;
}
console.info( fun1() );     	 //[ 'x1', 'y2' ]
console.info( fun1({}) );   //[ 'x1', undefined ] ,
							//{}  Cover  {y:"y2"} , Deconstruct default ,x=x1,y=undefined
  • Default values apply : Parameter is required
function fun2(args = new Error(" Parameters must be filled in ")){
    console.info(args);
}

fun2();
fun2("abc");

        1.4 Arrowhead function this

  • this object :
    • function Function this Represents the current object
    • Arrow function does not have its own this, Arrowhead function this See if there's a function in the outer layer ,
      • If there is , Of outer functions this It's the function of the inner arrow this,
      • without , In a browser environment this yes window; stay node.js Environment is the specified environment ( for example :vue)
  • establish demo03_2.js file
var name=" external ";
var user = {
    name : ' Inside ',
    show : function(){
        console.info(this.name)
    },
    show2 : () => {
        console.info(this.name) 
        console.info(user.name)
    }
}

user.show()         // Inside 
user.show2()        //undefined、 Inside  
  • establish demo03_3.html
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script>
    var name=" external ";
    var user = {
        name : ' Inside ',
        show : function(){
            console.info(this.name)
        },
        show2 : () => {
            console.info(this.name)
            console.info(user.name)
        }
    }
    user.show()         // Inside 
    user.show2()        // external 、 Inside ( On the browser side ,this Express window)
</script>

        1.5Map data structure (Map aggregate )

  • JavaScript The object of (Object), It's essentially a set of key value pairs (Hash structure ), But traditionally only strings are used as keys . This has brought a great limit to its use .
  • ES6 Provides Map data structure . It's like an object , It's also a set of key value pairs , however “ key ” Is not limited to strings . 

       1.6Set data structure (Set aggregate )

  • ES6 Provides a new data structure Set. It's like an array , But the values of the members are unique , There are no duplicate values .
//Set aggregate : Store unique data 
var set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(2);
set.add(1);

console.info( set );        //Set { 1, 2, 3 }
  • Filter the duplicate data in the array
var arr = [2, 3, 5, 4, 5, 2, 2];

// The way 1
var set2 = new Set();
// 1)  Traversal array , Add data to set
arr.map( s => set2.add(s) );
// 2)  Traverse set aggregate , Add to new array 
var arr2 = [];
set2.forEach( v => arr2.push(v) );
console.info( arr2 );       //[ 2, 3, 5, 4 ]

// The way 2
var arr3 = [ ... new Set(arr) ]
console.info( arr3 );       //[ 2, 3, 5, 4 ]

        1.7for...of Traverse

  • stay JavaScript in , There are many ways to traverse data , stay ES6 Provided in for…of , Used to unify the traversal of all data structures .
// Prepare the data 
var arr4 = ['x','y','z'];

var map4 = new Map();
map4.set("a","1111");
map4.set("b","2222");
map4.set("c","3333");

var set4 = new Set();
set4.add("m");
set4.add("n");
set4.add("L");

var obj4 = {
    name : "jack",
    password : "1234"
}
  • for…of Traverse
// for ... of 
for(let a of arr4){           // Traversal array 
    console.info(a);
}
for(let [k,v] of map4){      // Traverse Map,for…of Traversal in combination with deconstruction Map
    console.info(` The output data key is ${k} The value is ${v}`);
}
for(let s of set4){          // Traverse Set
    console.info(s);
}
for(let key of Object.keys(obj4)){   	// Custom objects cannot traverse , Need help keys convert to “ Key array ”
    console.info(` The key of the object is ${key}, The value is ${obj4[key]}`);
}
for(let [k,v] of Object.entries(obj4)){// You can also use entries convert to “ Key value pair ”
    console.info(`entries :  The key of the object is ${k}, The value is ${v}`);
}

// Add : Custom objects are handled specially ([Symbol.iterator]) You can also traverse , But there is bug, Imperfect , Refer to the following :
let obj = {
	// The original content 
	length: 3,
	[Symbol.iterator]: Array.prototype[Symbol.iterator]
}
  • JS The traversal already in

Traverse the way

describe

example

for Loop traversal

Normal cycle , It's often used to handle arrays

for (let i = 0;i < array.length;i++){

map()

Array chain operation function

array.map( fn ).xxx()

forEach()

Simplify arrays 、Map、Set The traversal

xxx.forEach( fn )

for…in

Traversing an object's enumerable properties in any order

for(let xx in obj) {}

for…of

Different data structures provide a unified access mechanism

for(let xx of obj) {}

  • map Use of functions
//map function  ,  Convert an array to a new array   
//var  New array  =  Old array .map(  Processing function  );		// Every element in the old array , All will pass “ Processing function ” To deal with 
// example : Will array  ['a','b','c']  Convert to string  'cba'
var m = arr4.map( s => {
    return s.toUpperCase();
}).reverse().join(",");
console.info(m);
  • forEach Use of functions
//forEach Traverse 
arr4.forEach(s => {         // Traversal array 
    console.info(s);
});
map4.forEach( (k,v)=> {     // Traverse Map
    console.info(`${k} ${v}`);
});
set4.forEach( k => {        // Traverse Set
    console.info( k ) ;
});
//obj4.forEach();           // I won't support it 
  • for…in Traversing objects
for(let prop in obj4){
    console.info( prop  + "," + obj4[prop]);
}

        1.8rest Parameters ( Shape parameter ...)

  • rest Parameters , Namely JS Variable parameters of . Before the last variable in the parameter list , Use “...”
 Function name ( Parameters 1,  Parameters 2, … variable )
function add(...num){               	// Variable parameters num, It's an array , The runtime stores all the arguments 
    var sum = 0 ;
    num.forEach( i => sum += i);
    return sum;
}
console.info( add(1,2,3) );

function count(args,...other){
    console.info(arguments.length);     // Although there are the number of parameters , Pseudo array , Out of commission forEach Traversal 
    console.info(other.length);         // Number of variable parameters , True array , have access to forEach Traversal 
}
count(1,2,3);

        1.9 Extension operator ( Actual parameters ...)

  • Extension operator (spread) Three points (...). It's like rest Inverse operation of parameter ,
    • The operation data is an array , Convert an array to a comma separated sequence of parameters .
    • The operation data is the object , Take out all traversable properties of parameter object , Copy to current object
var arr = ['a','b','c'];
function fun3(x,y,z){
    console.info( [x,y,z] );
}

fun3( arr );        //[ [ 'a', 'b', 'c' ], undefined, undefined ]
fun3( ...arr );     //[ 'a', 'b', 'c' ]

let z = { a: 3, b: 4 };
let n = { ...z };				// { a: 3, b: 4 }

2. modularization

  • stay ES6 Before ,JavaScript There has been no module (module) system , Cannot split a large program into interdependent small files , Put them together in a simple way .
  • stay ES6 Before , The community offers some solutions , There are two main kinds :CommonJS and AMD

        2.1ES5 CommonJS Solution

  • CommonJS A server-side solution (commonsJs Can be in node.js function )
  • CommonJS Need a compatible script loader , To support require and module.exports function , For module import and export .
  • Node.js Support this idea
  • Module export
module.exports = (a,b)=> a+b;
  • Module import
let add = require("./demo07_1");

console.info( add(1,2) );

        2.2ES6 module Implicit requirements

  • ES6 Strict mode is adopted automatically in the module of , Whether or not you add "use strict";.
  • The strict model mainly has the following limitations .

Variables must be declared before they can be used

A parameter of a function cannot have a property with the same name , Otherwise, the report will be wrong

Out of commission with sentence

Cannot assign to read-only property , Otherwise, the report will be wrong

Cannot use prefix 0 Represents octal number , Otherwise, the report will be wrong

Properties that cannot be deleted cannot be deleted , Otherwise, the report will be wrong

Cannot delete variable delete prop, Will report a mistake , Only attributes can be deleted delete global[prop]

eval It doesn't introduce variables in its outer scope

eval and arguments Cannot be reassigned

arguments Does not automatically reflect changes in function parameters

Out of commission arguments.callee

Out of commission arguments.caller

prohibit this Point to global object

Out of commission fn.caller and fn.arguments Get the stack of function calls

Reserved words added ( such as protected、static and interface)

        2.3ES6 module

  • A module , It is a file that exposes its properties or methods to other modules .
    • ES6 The module consists of two commands :export and import.
    • export command : Specify the external interface of the module . One export Statement declare once , There can be more than one file .
    • import command : Import other modules .

        2.4 The default is derived export default

  • Use import Command loading module , You must know the variable name or function name in the module , Otherwise, we can't load .
  • For the convenience of using the module , Module allows to use export default  Define default output . Only one default output is allowed for a module .
  • Default export variables
原网站

版权声明
本文为[Classmate Tao Ran.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203021428016522.html