ECMAScript learning Summary

What is the relationship ECMAScript and JavaScript?

  The former is the latter specification, which is an implementation of the former. Everyday occasions, the two are not interchangeable, respectively.

    ECMAScript 6 that is the sixth version of ECMAScript.

 

let command and const

  and let const command:

    let used to declare variables used like var, but there are big differences.

      const is used to declare a constant, constant is assigned must be declared immediately after, can not follow subsequent changes can not assign a value,

        Otherwise it will error. Other features are basically the same const and let.

          let the variable declaration and assignment is carried out simultaneously, is not declared in advance, do not mount on the window,

            It is not allowed to let the variables declared any action before let statement executed.

 

the console.log (B);      // 2     
the console.log (a);      // error, suggesting the absence of a 

the let a =. 1 ;
 var B = 2;

 

    let, declared const variable name can not be repeated declarations.

A. 1 = the let ;
 var A = 2 ;
 // directly given 

the let A =. 1 ;
 function A () {
     var A = 2 ; 
} 
// directly given

    let, const declaration is only valid within the let command block resides.

{
    let a = 10;
    var b = 1;
}

console.log(b);      //1
console.log(a);      //报错

    for loop loop expressions are suitable for let command. Further evidence let command is only valid in the code block.

for(var i=0;i<10;i++){}
console.log(i)      //10

for(let j=0;j<10;j++){}
console.log(j)      //报错

    

var a = [];
for (var i = 0; i < 10; i++) {
    a[i] = function () {
        console.log(i);
    };
}
a[6]();       //10     

    Var above code because the global variable assignment, effective only in a global scope and i, each loop will change the value of i, to the final accumulation cycle 10 is stopped.

      And for the inner loop the console.log (i), where i is the value of the function can only be found in the parent to find, finally found to have accumulated in 10 i, and outputs, to the output 10.

        So how do you make it output the corresponding index in the i value it?

var a = [];
for (let i = 0; i < 10; i++) {
    a[i] = function () {
        console.log(i);
    };
}
a[6]();  //6

    Let the above code uses to declare variables i, i Therefore, only the effective scope block level, and is effective within the round loop, each loop so the value of i at a block level are within the scope of an independent variable.

      And each cycle i can remember on a value of i, because the operation is carried out inside JavaScript, internal engine will remember the value of the previous cycle, calculated on the basis of the previous cycle.

        In addition to the A method, there is a method of using the closure.

var arr = [];
for (var i = 0; i < 10; i++) {
    (function(i){
        arr[i] = function(){
        console.log(i)
        }
    }(i))
}
arr[8]();      //8

    const and let temporary dead zone

      As long as there is a block-level scope and let const commands, variables declared it would bind this region, no longer subject to external influences.

 

The operator ... ES7

  Used for calling functions and objects:

function abc(a,b,c){
  console.log(a+b+c);
}
var arr = [3,4,5];
abc(...arr)

  The operator will become a parameter array sequence. Operators may also be used in conjunction with the normal function parameters.

function abc(a,b,c,d){
    console.log(a+b+c+d);
}
var arr = [3,4,5];
abc(2,...arr);

   Effect can be achieved by cloning the operator.

    Shallow clone:

let a = {
    num : 1 
}
let b = {
    num : 2
}
let c = {
    ...a,
    ...b        
}    

    Deep clone

let a = {
    num : 1 
}
let b = {
    num : 2
}
let c = {
    num : {
        ...a,
        ...b
    }     
}  

 

Deconstruction assignment

  Deconstruction of an array

let arr = [1,2,3];
let x,y,z;
[x,y,z] = arr;
//x = 1;y = 2;z = 3;

 

  Deconstruction of an object

let obj = {
    name : "Tom",
    age : 18,
    sex : "0"
}
let name,age,sex;
({name,age,sex} = obj )
//name = "Tom";age = 18;sex = "0";

Arrow function

  ES6 allows the use of "arrow" ( `=> ') defined function. You can write a very simple function.

var sum  = function(a,b){
    return a+b;  
}
//等同于
let sum  = (a,b) =>{
    return a+b;  
}
var fun = function(a,b){
    return {
        a:a,b:b
    }
}
//等同于
let fun = (a,b) => {
    return {
        a : a,
        b : b 
    }
}        
function fun(x){
    return function(y){
        return function(z){
            return x+y+z;
        }
    }
}        
//等同于
let fun = x => y => z => x+y+z;

 

Map structure

  Map data structure is like an object, is used to store the content.

    First, to use Map method to create a collection.

var map = new Map();
map.a = 1;
map.b = 2;
map.c = 3;
map.set("0","html");
map.set("1","css");
map.set("2","JavaScript");

map.get("0");//"html"
map.get("0");//true

 

     The map data set using the set method can add a key, the value may be acquired by get method. You can also use the delete method to delete the key selection.

 

  As a constructor, Map can accept an array as a parameter.

var Map = new new the Map ([[ 'name', 'John Doe'], [ 'Age', '20 is' ]]);
 // equivalent to the set ( 'name', 'John Doe');

 Examples of the properties and methods of operation

  size property

    Map size property returns total membership structure

let map = new Map();
map.set("name","Tom");
map.set("age","20");

map.size    //2

  Map.set(key,value)

    The method set key corresponding to the set property name attribute value of value, and then return the entire Map structure. If you already have a key value, the property value is updated, otherwise the newly generated property.

Map = the let new new the Map (); 

map.set ( "Key", 10);     // attribute name is a string, the value of the digital 
map.set (110, "120");     // attribute name is a number, the value of string 
map.set (undefined, "haha")     // property named undefined, the value of the string 

// can be written using a chain
map.set (. 1, "A")
  .set (2, "B")
  . set (3, "c") ;

  Map.get(key)

    get method to read the property value corresponding to the key, if no key, return undefined

function Fun () {the console.log ( "the Hello World !!!" );} 
the let Map = new new the Map () 
    .set (Fun, "the Hello" ); 

as map.get (Fun);     // calls to the function output "the Hello world !!!" 
map.get (haha); // undefined

  Map.delete(key)

    delete method removes an attribute, returns true. If the deletion fails, false is returned

function fun(){console.log("Hello world !!!");}
let map = new Map().set(fun,"Hello world")

map.delete(fun);    //true
map.delete(fun);    //false

  Map.clear()

    clear method clears all members, no return value.

let map = new Map();
map.set(1,1);
map.set(2,2);

map.clear();

Map of looping through

  for of

var Map = new new the Map ([[ 'name', 'John Doe'], [ 'Age', '20 is' ]]);
 // equivalent to the set ( 'name', 'John Doe'); 
for ( var I in map) { 
    the console.log (I) 
} 
// standard output the map object name 
for ( var index of map) { 
    the console.log (index); 
} 
// add the output of the array into the key-value 
for ( var name map.entries of ()) { 
    the console.log (name) 
} 
// outputs a corresponding value pairs 
for ( var [Key, value] of map.entries ()) { 
    the console.log (Key, value) 
} 
// key-value pair corresponding to the output
for ( var Val of map.values ()) { 
    the console.log (Val) 
} 
// value of the output key-value pairs

 

class

  6 ES class can be seen as another way constructor. Its data type is function.

class Hyh{}
typeof Hyh; //"function"

  When using the new command is used directly for lei, and usage of the constructor exactly the same.

class ID{
    constructor(name,age){
        this.name = name;
        this.age = age;  
    }
    logFun(){
        console.log("name:"+this.name+"\n"+"age:"+this.age);
    }
}

var Tom = new ID("Tom",21);
Tom.name    //"Tom"
Tom.age    //21

Tom.logFun();     
//name:Tom
//age:21

  Tom is the instance ID, and Tom's constructor method is the constructor method ID class prototype, new methods of a class can be added to the prototype class. May be added to a plurality of classes by the method of Object.assign method once.

Object.assign(ID.prototype,{
    toName(){},
    toAge(){} 
})

class inheritance

  class inheritance can be achieved by the extends keyword

class Code extends ID{}

  After inheriting can call inherited methods and properties

var Jack = new Code("Jack","20");
Jack.name;    //"Jack"
Jack.logFun();
//name:Jack
//age:20

  You can inherit the parent class in function after adding new attributes and their parameters, the parameter information received by the configuration of the parent class method super

class ID{
    constructor(name,age){
        this.name = name;
        this.age = age;  
    }
    logFun(){
        console.log("name:"+this.name+"\n"+"age:"+this.age);
    }
}

class Code extends ID{
    constructor(name,age,color){
        super(name,age);    //用来继承父类参数接收
        this.color=color
    }
}

var color = new Code("Jack","20","black")


Promise objects commitment

  It is an asynchronous programming solution than traditional solutions - more rational and more powerful - callback functions and events. Mainly used for asynchronous message processing.

  It is a container, which holds the event will end sometime in the future (usually an asynchronous operation) results. Promise to provide a unified API, a variety of asynchronous operations can be handled the same way.

Two characteristics Promise objects:

  1, the state of the object is not affected by the outside world. Promise object represents an asynchronous operation, there are three states: pending (in progress), funlfilled (been successful) and rejected (failed). Only results of asynchronous operations, you can decide what kind of current state, no other operations can change that state. Promise This is the origin of the name, which in English means "commitment", he said other means can not be changed.

  2, once the state change, will not change, at any time this result can be obtained. Promise object changes state, only two possibilities: from pending changes to funlfilled from pending and becomes rejected. As long as these two things happens on the solidification state, will not be changed and will keep the result, then you become resolved (finalized). If the change has occurred, you add objects to Promise callback function will immediately get this result, which is the event (Event) is completely different, the characteristics of the event is, if you missed it, go listen, is not result.

Basic Usage

  Promise object is a constructor to generate Promise instance.

Promise = the let new new Promise ( function (resolve, reiect) {
     IF ( "asynchronous operation if successful" ) { 
        resolve (value);     // perform functions successfully resolve 
    } the else { 
        reject (error);     // execution failed reject function 
    } 
} )

  Promise constructor takes a function as a parameter, two parameters of the function are a function failure and reject resolve work function. They are two functions provided by the JavaScript engine, you do not have to deploy.

  Function is to resolve the role of the state of the object from Promise "unfinished" to "success" (i.e., changed from pending resolved), then the asynchronous call successful operation, and the result of the asynchronous operation, to pass out as a parameter; Reject function returns the state of the object from Promise "unfinished" to "failed" (i.e., changed from pending Rejected), invoked when an asynchronous operation fails, and the asynchronous operation errors may be, as a parameter to pass out.

then () method

  After generating Promise example, can destroy the function specified state and a rejected state is resolved by then Methods.

promise.then(function(value){
    console.log("成功了!"+value);
},function(error){
    console.log("失败了!"+error);
})

  After then call returned a Promise object. Then you can write then chained the wording in the new method of Promise, then the method specified callback function will wait for the new Promise object state changes.

promise.then(function(data){
    return data + 10;
},function(){
}).then(function(data){
    console.log(data);
},function(err){
    console.log(err); 
})

  Promise use to write a ajax

var btn = document.getElementById("btn");
var box = document.getElementById("box");

btn.onclick = function(){
    var promise = new Promise(function(resolve,reject){
        ajax('./16.txt',function(data){
            resolve(data)
        },function(err){
        reject(err)
        })
    })
    promise.then(function(data){
        box.innerHTML = data;
    },function(err){
        box.innerHTML = err;
    })
}

function ajax(url,fnSucc,fnErr){
    var xhr = new XMLHttpRequest();
    xhr.open('GET',url,true);
    xhr.send();
    xhr.onload = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
        fnSucc(xhr.responseText);
        }else{
        fnErr(xhr.status);
        }
    }
}        

 

   

 

Guess you like

Origin www.cnblogs.com/yeming980912/p/11270958.html