ES6 (notes)

ES6

New method string

  • {} indicates new unicode support
  • String.fromCodePoint () returns the corresponding unicode character from
  • String.raw slash also returns escaped string String.raw``\(tag function form, as the operator can be placed before the string templates)
  • codePointAt return the correct unicode code points
  • repeat(n)Returns a new string representation speak original string repeated n times
  • padStart(5,"a"), padEnd()Fill is insufficient
  • startsWith("a",5), endsWith()To determine whether there is a string

Regular Extended

  • Add // u, can correctly identify unicode characters greater than 0xffff, you can check whether to set an example by unicode property
  • // y // g with the same function, but // y must successfully match the match began, the role is to allow the head to match the entry into force in all the matches, see if the property is set by sticky
  • // s so can match any single character (not seem to need may be)
  • First assertion : / \ d + (? = W) / ug, only matched numbers w front, / \ d + (?! w ) / ug not match the preceding figures w
  • Trailing asserted : / \ d + / ug, only matched numbers behind w (<= w?)
  • Named group match
const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;

const matchObj = RE_DATE.exec('1999-12-31');
const year = matchObj.groups.year; // 1999
const month = matchObj.groups.month; // 12
const day = matchObj.groups.day; // 31

You may also be used as replace the corresponding name

let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;

'2015-01-02'.replace(re, '$<day>/$<month>/$<year>')

Numerical extension

Extended Math

  • Math.trunc()Removing the fractional part, returns the integer part, non-numeric type call Number
  • Math.sign()Analyzing negative or 0
  • Math.cbrt(2)Cube root calculation, the use of non-numeric type Number Conversion
  • Math.hypot()All parameters and returns the square root of the square

Extended Functions

  • Function parameters having a block-level scope
  • ES6 only tail call optimization is enabled in strict mode
  • ES2017 function parameters allows the tail comma
  • ES62019 allowed to catch not carry parameters

Array expansion

  • Array.from()The third parameter can be passed to bind this
  • Examples of the method copyWithin(target,start,end)from the start position (the lower index value) to replace the element into the end position of the target
  • === strict operational use indexof judgment, would NaN error of judgment, includes methods do not have this problem
  • Using the flat()method of the array into a one-dimensional array, the incoming parameter specifies the number of layers of flattened, returns a new array

Object extension

  • ES6 provisions, the prototype approach all class types are not enumerable
  • Object convenient order
    • First convenient numeric keys in ascending order
    • Traversal string key and then, ascending
    • Finally convenience Symbol key, press Joined ascending order

Object new method

  • Object.is()Strict determine whether equal, === compared to NaN, + 0 / -0 problem is optimized
  • Object.assign(target,source)Copy the source object to the target in
  • Object.fromEntries()It is Object.entries()the inverse operation, for an array of key-value pairs into target
Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])
// { foo: "bar", baz: 42 }

One is to use the query string into an object

Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
// { foo: "bar", baz: "qux" }

Symbol

  • property description View description
  • Symbol.for()There will return, is not created. Symbol.keyFor()Query returns the corresponding description of the key

Set and Map

  • WeakSet can use to store temporary collection of objects (only store objects, similar to the structure and Set), garbage collection does not consider WeakSet references to objects, not size can not be traversed
const ws=new WeakSet();

  • WeakMap only keys stored in object format (only for the key name), using the stored key WeakMap called weak reference, there is no traversal, no size

Proxy

  • Proxy.revocableExamples of a cancel return
let {proxy, revoke} = Proxy.revocable(target, handler);

Promise objects

  • If you have resolve and then throw an error is invalid
  • Recommended catch, instead of directly using the second parameter
  • ES2018 introduced Regardless finally, that is, the callback will be called regardless of the outcome of Promise
  • ES2020 introduction Promise.allSettled()method, you must complete before calling all instances, regardless of success or failure (proposal)
  • Promise.any()(As long as there is a fullfiled will become fulfilled state) is similar Promise.race()(as long as there is a refusal to be resolved or will end) but will not be rejected and an end. This method is currently a proposal

Generator

  • yield expression if used in another expression inside, inside parentheses must then
console.log("hello" + yield 123);
  • If the yield is not specified is returned by the next value of the next undefined
  • generator function does not return a return value to traverse
  • To capture the error was internal generator at least once next, otherwise external throws an error (the first execution method can be seen next start generator), internal generator arranged try ... catch block does not affect the next throw after throw an error traversal
  • generator implement a state machine
  function clock(){
                while(true){
                    
                    yield;
                    console.log("没锁");
                    yield;
                    console.log("锁住了");
                }
            }

async function

  • async objects and return to promise all other internal asynchronous operations will be performed then executing the method of
  • async is the syntactic sugar generator, generator + self-executing function is async
function spawn(gen){
        //    接受generator,返回promise
        return new Promise(function(resolve,reject){
            let genF=gen();
            function step(callback){
                let nextF;
                try{
                    nextF=callback();
                }
                catch(e){
                    reject(e);
                }
                if(nextF.done)return;
                Promise.resolve(nextF.value).then(e=>{
                    // 这样返回的还是promise
                     step(function(){
                        return genF.next(e);
                    })
                },e=>{
                    step(function(){
                        return genF.throw(e);
                    })
                })
            }
            step(function(){return genF.next(undefined)});
        })
       }

Class class

  • The method defined in a class are not enumerable
  • The class attributes may be defined within this write-use constructor, it may be written directly on top of the class

Module

  • Loading and CommonJS runtime copy output is the value of the cache and, Module1 is loaded compile time, enables dynamic read-only reference. import will be carried out to enhance the (execution import compile phase, and then the code before running).
  • ComonJS can be dynamically loaded (require in the end when the load module which runs only knows), Moudle do
//CommonJS的动态加载,源于CommonJS的运行时加载
const path='./' + filename;
const myModule=require(path);

  • This is not global top Module (valid only in the module scope), is undefined, CommonJS this refers to the current top-level module module

Module loading implement

  • JavaScript introducing Module, load changes such as adding defer ordinary script, finished rendering load
  <script type="module">
            import a from './index';
            console.log(a);
    </script>

  • ES6 module loading CommonJS, Node module.exports automatically as the default output module attributes, i.e. equivalent to export default xxx.
  • CommonJS of cyclic loading Once a module is "cyclic loading", has been performed on only a subset of, the execution is not yet part of the output.

Programming Style

  • let substituted var
  • Priority use const
  • String is recommended to use single quotes
  • Priority use destructuring assignment
  • Single line object does not end with a comma, multi-line objects terminated with a comma
  • Static objects, can not be changed once it is determined, if we must add an attribute withObject.assign()
  • Object properties and methods to make use of simple expressions
  • Arrow immediately execute the function written in functional form, function instead of using the arrow anonymous function, the function configuration items on an object, the last argument put
  • Not function arguments object acquisition variable vivo
  • If you simply save the key-value pairs using Map
  • Try to use Class

Decorator (decorator) - belong to the current draft, the need to support babel

  • Decorators can only be used in class, the function can not be used, because there is a problem function to enhance the function
  • core-devorator.js is a three-way module, provides several common decorator
    • @autobind that this object the original object binding method
    • @readonly the property or method is not writable
    • Methods @override check subclass, the correct method of covering the same name Frey
    • @deprecate (alias @deprecated) console displays a warning, indicating that the method would repeal
  • traits-decorators can achieve mixing, and a method to prevent the same name conflict, mixed exclude certain methods, starting alias mixing method or the like.
import { traits } from 'traits-decorator';

class TFoo {
  foo() { console.log('foo') }
}

const TBar = {
  bar() { console.log('bar') }
};

@traits(TFoo, TBar)
class MyClass { }

let obj = new MyClass();
obj.foo() // foo
obj.bar() // bar


//混入实现方法
function mixin(...list){
  return function(target){
    Object.assign(target.prototype,...list);
  }
}

Published 85 original articles · won praise 62 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_36754767/article/details/103551689