当前位置:网站首页>Notes on learning Es5 and ES6

Notes on learning Es5 and ES6

2022-06-11 07:05:00 Boiled wine cos

ES5 grammar

Strict mode
  1. Must use var Life variable

  2. It is forbidden to use... In custom functions this Point to window object

  3. establish eval Scope

var str = 'NBA';
eval('alert(str)')
// Can parse the string inside and execute 
// but eval The variables in are automatically promoted to the global level 
// So use the strict pattern , take eval Created scope , Into the private 
  1. Objects cannot have properties with duplicate names
Json object
json.stringfy(obj/arr)
// Convert an object or array to json object 
json.parse(json)
// Empathy 
  1. json It's a format for transmitting data
  2. You can easily get the properties of the object
object package
  1. object.create(prototype ,[descriptors])
    
    obj ={
          username : 'jjr', age:'1'}
    
    var obj1={
          }
    
    obj1 =object.create(obj, {
          
        sex:{
          
            value:'boy'// Actual specified value 
            writeable:true// Can I modify , The default is faluse
            configurable:true// Can it be deleted , The default is faluse-- delete obj1.sex
             enumerable:true// Identify whether the attribute can be used for in To enumerate   The default is false 
            //for(var i in obj1){
          
            //console.log(i) Will it sex attribute 
        //}
        }
    }
    )
    
  2. object.defineproperties(obj,description)
    // Used to extend attributes 
     var obj ={
          username : 'jjr', age:'1'}
     object.defineproperties(obj, {
          
        fullname:{
          
         get:function(){
          
         	return this.username + " " +this.age;
         } // This is how to get the value of the attribute 
         set:function(data){
          
         // Listening extended properties , Automatically called when the extended attribute callback , Inject the changed value as an argument 
     	}
         
    
  3. get propertyname(){
          }
    // The callback function used to get the current property value 
    set propertyname(){
          }
    // Callback function used to monitor the current property value change 
    
array Extension of arrays
indexOf(value) take value The first subscript appears 
lastindexof() take value The last subscript appears 
foreach((item , index)=>{}) Traversal array 
map((item , index)=>{}) Can return a new array ( More than traversal )
filter((item , index)=>{}) Can return a new array 
Function extension

binding obj use call and apply

var obj={username : 'jjr', age:'1'}
function foo(data){
consolo.log(this,data)
}
foo.call(obj) Can be bound 
foo.apply(obj)
 It is the same without parameters 
foo.call(obj,33)
// Start directly with the second parameter , One by one 
foo.apply(obj,[33])
// The second one must be the array passed in to be placed in the array 
foo.blind(obj)
blind() Is to return the function to , The current function will not be called immediately 
 So there is  var bar = foo.blind(obj)
 There's more bar(data)
 Can be combined 
foo.blind(obj ,33)()

Callback function : Not called immediately , So want to use blind

ES6 grammar

const and let
  1. Valid in block level scope
  2. Can not repeat the statement
  3. No preprocessing , There is no block level promotion
  4. stay for Use... In circulation let
  5. Use let replace var Is the trend

Click the callback function , In the practice queue , Check "execute" after finishing in the main queue // You can avoid using closures

  1. Do not modify
  2. Other features are the same as let
  3. Save data that doesn't need to be changed
  4. If it's an object , The value of the attribute can be changed , But the name and number of attributes cannot be changed
Deconstruction and assignment of variables
  1. Extract data from an object or array , And assign to variable ( Multiple )

  2. Object's deconstruction assignment

    let {n,a}={n:'tom',a:12}
    // Must be an existing attribute 
    let {n:newa,a}={n:'tom',a:12}
    // Change of name 
     You can take the data directly 
    let {n}={n:'tom',a:12}//n:'tom'
    let {a}={n:'tom',a:12}//a:12
    
  3. Deconstruction and assignment of arrays

    let [a,b]=['tom',12]
    // You can't take the data directly 
    // Make room for it 
    let [,,,a,b]=[1,2,3,4,5]//a=4,b=5
    let [,,a,b]=[1,2,3,4,5]//a=3,b=4
    let [,,...a]=[1,2,3,4,5]//a=[3,4,5]
    // The ellipsis must be the last 
    
  4. purpose : Assign values to multiple formal parameters

  5. var obj={username : 'jjr', age:'1'}
    function foo({username,age}){
     consol.log(username,age)
    }
    foo{obj}
    
Template string
  1. Simplify string splicing
  2. Template string must use `` contain
  3. The changed part must be $(XXX) Definition
let obj={
    username:'kobe',age:39}
let str = ' My name is '+obj.usename+', My age this year is '+obj.age
let str1 = ` My name is $(obj.usename), My age this year is $(obj.age)`
Simplified objects obj Internal writing
  1. Omit attribute values of the same name

  2. Omit the of the method function

  3. let x=1;
    let y=2;
    let point ={
          
    	x,
    	y,
    	setX(x){
          this.x=x}
    }
    let point1 = {
          
        x:x,
    	y:y,// The original way of writing 
        // Therefore, attributes with the same name can be left blank 
        getx:function(){
          
            // It can be omitted :function
            return this.name;
        }
        // It can be changed into the following mode 
        getx(){
          
            return this.name;
        }
    }
    
Arrow function
  1. effect : Defining anonymous functions

  2. No parameters :()=>console.log(‘xxx’)

  3. The case of a parameter i=>i+2

  4. Greater than one parameter (i,j)=>i+j

  5. When the function body does not use braces, it returns the result by default

  6. If the function has multiple statements ( That is, when there are braces ){}, If there is something to return , Manual return required

  7. Usage scenarios are often used to define callback functions

  8. characteristic

    1. concise

    2. Arrow function does not have its own this, Arrowhead function this What is not called is determined by , But the object in which it is defined is its this

    3. Of a regular function this That is, whoever calls it will use it

    4.  Expand your understanding of :
       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 , be this yes window
      
let fun = function (){
    
	console.log('arrow')
}
let fun1 = () =>console.log('arrow');
fun1()

let fun2 = a =>console.log('a');
fun2('aaa')

let fun3 = (a,b) =>console.log(a,b);
fun3(25 ,26)

let fun3 = (a,b) =>{
    
    console.log(a,b);
    return a+b;
}

let fun4 = (a,b) =>a+b;
let sum = fun4(25 ,26)
// No, return Words , The return value defaults to undefined
Three point operator
  1. Also called … Operator

  2. reset Variable parameters , The position of the parameter

    The three-point operator can only be collected at the end (in function)

    function fun(a,...values){
          
    	console.log(arguments);
        //arguments.forEach(function //(item,index){
          
            //console.log(item,index)
        //}) so arguments Is a pseudo operator 
        // also callee Self callback method of 
        console.log(values);
        values.forEach(function (item,index){
          
            console.log(item,index)
        })
        // A true array can use the array method 
    }
    fun(1,2,3)
    
  3. Extension operator , Actual parameters

    It is equivalent to traversing the array and getting each value

    let arr1 = [1,3,5]
    let arr2 = [2 ,...arr1,6]
    arr.push(...arr1)
    
Parameter defaults

When no parameter is passed in, the default value in the formal parameter is used by default

function point(x = 1,y = 2){
    
	this.x=x;
	this.y=y
}
let point = new point(23,35);//x=23,y=35
let point1 = new point(35);//x=35,y=2
let point1 = new point();//x=1,y=2
promise object
symbol
  1. Original data type (string, number, Boolean ,null, undefined , object )

  2. symbol Is a newly added data type

  3. symbol The value of the property is unique , Solve the problem of naming conflict

  4. symbol Value cannot be calculated with other data , Including the same string splicing

  5. for in and for of It doesn't traverse symbol attribute

  6. Use

    1. call symbol Function to get symbol value

       establish symbol Property value 
      let symbol = Symbol();
       Unwanted new
      console.log(symbol)//symbol()
      
    2. The reference mark

      let symbol1 = Symbol('one')
      let symbol2 = Symbol('two')
      console.log(symbol1,symbol2)
      //Symbol(one) Symbol(two)
      
    3. Symbol Types can also be used to define a set of constants , Make sure that the values of these constants are not equal .

    4. built-in symbol value

      In addition to defining what you use Symbol Unexpected value ,es6 It also provides 11 Built in Symbol value , Point to the internal usage of the language

    5. Symbol.iterator

      Object's Symbol.iterator attribute , Point to the default iterator method with the object ( Later on )

let obj ={
    username :'kobe' ,age:39}
obj[symbol] = 'hello'
console.log(obj)
//Symbol():'hello'

const mySymbol = Symbol();
const a = {
    };

a.mySymbol = 'Hello!';
a[mySymbol] // undefined
a['mySymbol'] // "Hello!"
// In the above code , Because the dot operator is always followed by a string , So it won't read mySymbol The value referred to as the identity name , Lead to a The property name of is actually a string , Instead of a  Symbol  value .

// actually JavaScript All properties of an object are strings , But the value of the property can be any data type .

// Empathy , Inside the object , Use  Symbol  When the value defines a property ,Symbol  The value must be in square brackets .
let s = Symbol();

let obj = {
    
  [s]: function (arg) {
     ... }
};

obj[s](123);
Iterator Iterator
  1. iterator( Iterator means ) It's an interface mechanism , Provide a uniform for different data structures Access mechanism
  2. effect
    1. Provide a unified framework for all kinds of data structures , Simple access interface
    2. Enables members of a data structure to be arranged in a certain order
    3. es6 Creates a new traversal command for of loop ,iterator Interfaces are mainly used to attack for of Use
  3. working principle
    1. Create a pointer object ( Traverser object ), Point to the actual location of the data structure
    2. First call next Method , The pointer automatically points to the first member of the data structure
    3. Next, every time you call next Method , The pointer will go all the way back , Know to point to the last member
    4. Each one is used next Method returns a containing value and done The object of
      1. value: The value of the current member
      2. done: Boolean value
    5. value The value that identifies the current member , The Boolean value corresponding to dong'a indicates whether the current data structure has been traversed
    6. When the traversal is over, it returns value yes undefined,done The value is false
  4. Original possession iterator Interface data ( It can be used for of Let's do the traversal )
  5. Expand your understanding of
    1. When deployed on the data structure symbol.iterator When the interface of , This data can be used to for of Traverse
    2. When using for of When traversing the target data structure , The data will automatically go to symbol.iterator attribute
    3. symbol.iterator Property points to the object's default iterator method
      1. array
      2. arguments
      3. set Containers
      4. map Containers
function myIterator(arr){
    
    let nextIndex=0
    return {
    
        // Traverser object 
        next:function(){
    
            return {
    
nextIndex <arr.length ? {
    value:arr[nextIndex++],done:false} : {
    value:undefined done:true}
            }
        }
    }
}
// Prepare a data 
let arr = [1,4 7,'abc']
let iteratorObj=myIterator(arr);
iteratorObj.next();
iteratorObj.next()

The above will be es6 Add to data type in advance

take iterator Interface is deployed to the specified data type , You can use for of Loop traversal

Already exist ( Array , character string ,arguments,set and map Containers )

let arr = [1,4 7,'abc']
for(let i of arr){
    
	console.log(i)
}

let str = 'abcde'
for(let i of str){
    
	console.log(i)
}

function fun(){
    
	for(let i of arguments){
    
	console.log(i)
	}
    //arguments It's a pseudo array , General methods without arrays , So there was no for each Method 
}
fun(1,4,5,'abc')

There is no deployment on the object iterator, So it can't be used for of Method to traverse

When using the three-point operator and deconstruction assignment, you use by default iterator Interface

let arr2=[1,6]
let arr3=[1,...arr2,6]
// Ergodic arr2 Value 
 Isomorphic deconstruction assignment 
Closure
  1. Concept
    Closure function : Functions declared in a function , It's called a closure function .

  2. Closure : Internal functions always have access to the parameters and variables declared in the external function in which they reside , Even if the external function is returned ( End of life ) After that .

  3. characteristic

  4. Make it possible for external access to function internal variables ;

  5. Local variables are resident in memory ;

  6. You can avoid using global variables , Prevent contamination of global variables ;

  7. Memory leaks can occur ( There's a block of memory that's been occupied for a long time , Without being released )

  8. Closure creation :­­­
    Closure is to create a separate environment , The environment inside each closure is independent , Mutual interference . Closures leak memory , Every time an external function executes Hou , The reference address of the external function is different , Will create a new address . However, the current active object contains data referenced by an internal subset , So at this point , This data is not deleted , Keep a pointer to the internal active object .
    ————————————————
    Copyright notice : This paper is about CSDN Blogger 「 Second brother Yang 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
    Link to the original text :https://blog.csdn.net/weixin_43586120/article/details/89456183

Symbol.Interator

It is equivalent to deploying on the specified data structure iterator Interface

When using for of To traverse a data structure , First of all Symbol.Interator, If you find it, go through it , You can't traverse without (obj is not iterator)

let targetData={
    
	[Symbol.Interator]:function(){
    
         let nextIndex=0
    return {
    
        // Traverser object 
        next:function(){
    
            return {
    
nextIndex <this.length ? {
    value:this[nextIndex++],done:false} : {
    value:undefined done:true}
            }
        }
    }
    }
}
Generator function
  1. es6 One of the solutions to a problem

  2. generator Function is a state machine , It encapsulates data in different states

  3. Used to generate the traverser object

  4. Pause function ( Lazy evaluation ),yield Can pause ,next Method can start , Every time I return yield The result of the expression after

  5. characteristic

    1. function There is a model number between and the function name

    2. For internal use yield Expressions to define different states

    3. function * generatorExample(){
      let result = yield 'hello'// The status value is hello
      //result The value is undefined, namely yield Return to normal will be undefined
      // But there are next( value ) Will be sent back 
      yield 'generator'// The status value is generator
      }
      
    4. generator Function execution returns a pointer object ( Traverser object )( yes iterator), Instead of executing the logic inside the function

    5. call generator The return value of the function next When the method is used , The logic inside the function begins to execute , encounter yield The expression stops , return {value:yield The expression after / The return value of the execution result of the statement /undefined,done:false/true( Traversal complete )}

    6. Call again next Method will stop from the last time yield Start at , Until the last

function * myGenerator(){
    
console.log(' Start execution ')
yield 'hello'// state hello
console.log(' After suspension , Carry on ')
yield 'generator'// state generator
}
let MG = myGenerator()
// Returns a pointer object 
//MG.next()
console.loge(MG.next())
//{value:hello,done:false}
let obj={
    uername:'jjr',age:'18'}
obj[Symbol.interator]=function*mygenerator(){
    
yield 1;
yield 2;
yield 3;
}
for(let i of obj){
    
console.log(i)
}
//1 2 3 
function getNews(url){
    
$.get(url,function(data){
    
console.log(data// Data obtained )
           let url=''+data. data 
            SX.next(url)
})//jquery method import
}
function * sendXml(){
    
    let url=yield getNews( website )
    yield getNews(url)
}
let SX = sendXml();
SX.next();
      
async function (ES7)
  1. To solve the problem of asynchronous callback in a real sense , Synchronous process to express the operation of a department

  2. The essence :genenrator The grammar sugar of ( Give Way generator The method is more perfect )

  3. grammar

    async function foo(){
          
        await // Asynchronous operations 
        // Wait until the asynchronous operation is completed , Carry out the next 
        await // Asynchronous operations 
    }
    
  4. characteristic

    1. No need to be like generator Function to call next Method , encounter await wait for , When the current operation is completed, it will be executed
    2. It's always going back to promise object , It can be used then Method to proceed to the next step
    3. async When replaced Generator Asterisk of function ,await Replaced Russian Generator Of yield
    4. More semantically clear , Easy to use , No side effects and adverse reactions
async function foo(){
    
    return new Promise(resolve=>{
    
        setTimeout(function(){
    
            resolve()
        },2000)
        setTimeout(resolve,2000)
    })
}
async function test(){
    
    console.log('begin',new Date().toTimeString)
    await foo()
    // There is no need to next, Automatically 
    console.log('end',new Date().toTimeString)
}
  1. await The return value of

    function teat2() {
           
        return 'xxx'
    } 
    async function asyncPrint(){
          
     	let result = await teat2()  console.log(result)
    }
    asyncPrint()
    //"xxx"
    
    async function asyncPrint(){
          
        let result = await Promise.resolve('promise');
    	console.log(result)
    	result = await Promise.reject('fail')
    	console.log(result)
     }
     asyncPrint()
    //promise
    // Uncaught (in promise) fail
    
class
  1. adopt class Defining classes , Implementation class inheritance (js We inherited from the prototype )
  2. Pass in the class constructor() Define construction method
  3. adopt new Create the real column of the class
  4. adopt extends Implementation class inheritance
  5. adopt super() Call the constructor of the parent class
  6. Override the general methods inherited in the parent class
class Person {
    
	constructor(name,age){
    
        this.name=name;
        this.age=age
    }
    // Class 
    showName(){
    
        console.log(this.name)
    }
    // On the prototype of the real column object , Not on the object itself 
}
let person = new Preson('kobe',39)
class starPerson extends Person(){
    
    constructor(name,age,salary){
    
        super(name,age)
        // Identifies the constructor that calls the parent class 
        //this.name=name;
        //this.age=age
        // Follow java equally 
        this.salary = salary
        
    }
    showName(){
    
        console.log(this.name,this.age,this.salary)
    }
    // Method coverage / Override of the method of the parent class 
}
  1. Pass in the class constructor() Define construction method
  2. adopt new Create the real column of the class
  3. adopt extends Implementation class inheritance
  4. adopt super() Call the constructor of the parent class
  5. Override the general methods inherited in the parent class
class Person {
    
	constructor(name,age){
    
        this.name=name;
        this.age=age
    }
    // Class 
    showName(){
    
        console.log(this.name)
    }
    // On the prototype of the real column object , Not on the object itself 
}
let person = new Preson('kobe',39)
class starPerson extends Person(){
    
    constructor(name,age,salary){
    
        super(name,age)
        // Identifies the constructor that calls the parent class 
        //this.name=name;
        //this.age=age
        // Follow java equally 
        this.salary = salary
        
    }
    showName(){
    
        console.log(this.name,this.age,this.salary)
    }
    // Method coverage / Override of the method of the parent class 
}
原网站

版权声明
本文为[Boiled wine cos]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110656426249.html