ES6,ES7~ES10 overview

350 阅读2分钟

1.ES6

  • meta programming: Proxy (Revocable proxy)
  • meta programming: Reflect
    • Reflect.apply vs Function.prototype.call/apply/bind
    • Reflect.construct
    • Reflect.defineProperty & deleteProperty
    • Reflect.get & Reflect.set
    • Reflect.getOwnPropertyDescriptor
    • Reflect.getPrototypeOf
    • Reflect.has
    • Reflect.isExtensible & preventExtensions
    • Reflect.ownKeys
  • Iterator
    • [Symbol.iterator](){...}
  • Generator
    • yield
    • improvement: async-await
  • enhanced features
    • RegExp
      • sticky
      • unicode
    • Array
      • for...of
      • Array.from / of
      • Array.prototype.fill / find / findIndex
    • Object
      • enhanced properties(object literals): variable and function member shortcut
      • Object.assign
    • Function
      • default parameter
      • rest parameter: fn(...rest)
      • spread operator: [...[1,2]] or {...{a:1,b:2}}
  • [Weak]Set & [Weak]Map
  • Destructure (Array & Object destructure)
  • Class
  • Scope
    • let & const
    • var
  • Module
    • import
    • export
  • Promise
    • resolve & reject
    • then & catch
    • Promise.all & Promise.race
    • Promise.resolve & Promise.reject
  • Template (string literals and tag Literals)

1.iterate array with for...in / for...of

// for... / forEach / map / every
let arr = ["Prefect","Day","feat.","R.I.B."];
arr.origin = "The Deysion";

for(const idx_or_property in arr){
    console.log(idx_or_property);   //0 1 2 3 origin
}

for(const idx of arr){
    console.log(idx);   //"Prefect","Day","feat.","R.I.B."
}

2.Array.from()

//transform array-like or iterable object(including Set/Map) into array
//format: Array.from(arrayLike [, mapFn [, thisArg]]): mapFn do not use arrow function
let arrayLikeObj = {
    0:"Baptism",
    1:"Paul",
    2:"Cardall",
    length:"3"
};
Array.from(arrayLikeObj); // ["Baptism", "Paul", "Cardall"]

class SongsCollection {
    constructor(...songsList) {
        this.songs = songsList.length>0 ? songsList : ['We Found Love','Triumph of Love'];
    }
    *[Symbol.iterator]() {
        for(const song of this.songs) {
        	yield song;
        }
    }
}
const mySongs = new SongsCollection();
Array.from(mySongs); // ["We Found Love", "Triumph of Love"]
// use all parameter
Array.from(mySongs,function(item){  // ["item-my-favorite", "item-my-favorite"]
    return `item-${this.tag}`
},{ tag:"my-favorite" });

// another old way: only work for array-like obj not for iterable obj
[].slice.call(arrayLikeObj);

3.Array.prototype.fill / find / findIndex

// MDN: arr.fill(value[, start[, end]]) 
const array = [1, 2, 3, 4];
array.fill(0, 2, 4); // [1, 2, 0, 0]
array.fill(5, 1); // [1, 5, 5, 5]
array.fill(6); // [6, 6, 6, 6]

// MDN: arr.find(callback(element[, index[, array]])[, thisArg]), findInex same as find
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));

4.RegExp: unicode & sticky

// unicode
const regexUnicode = new RegExp('\u{1024}','u'); // or /\u{61}/u
regexUnicode.unicode; // true
regexUnicode.source; // ဤ
/\u{1024}+/u.test("guan-ဤဤ-45"); // true

// sticky
const str = 'when they told me you were gone';
const regex = new RegExp('they','y');
regex.lastIndex = 5;
console.log(regex.sticky); // true
console.log(regex.test(str),regex.lastIndex); // true 9
// lastIndex is 9 : next match start from 9 as index of str
console.log(regex.test(str),regex.lastIndex); // false reset lastIndex to 0
// reset after match failure: reset laseIndex = 0

5.Reflect

// 1.Reflect.apply(target, thisArgument, argumentsList)
Reflect.apply(function(...args){
    console.log(...args,this.season); // m o o n winter
},{
    season:"winter"
},['m','o','o','n']);

// 2.Reflect.construct(target, argumentsList[, newTarget]),same as new operator
function Rise(name){
    this.name = name
}
const riseOne = new Rise("hello");
const riseTwo = Reflect.construct(Rise,["world"]);
console.log(riseOne.__proto__ === riseTwo.__proto__, riseOne.__proto__ === Rise.prototype);
// result: true true

function WhereClass(location){
    this.where = location;
}
const riseThree = Reflect.construct(Rise,["!!!"],WhereClass);
console.log(riseThree.__proto__ === WhereClass.prototype); // true
riseThree.name; // !!!
riseThree.where // undefined

// same result as this:
let obj = Object.create(WhereClass.prototype)
Rise.apply(obj, ["!!!"]);

// 3.Reflect.preventExtensions, like Object.preventExtensions()
// extension: just can not add new properties
// Object.freeze: can not add, delete and change property 

2.ES7

  • Array.prototype.includes()
  • Math.pow

1.Math.pow

console.log(Math.pow(7, 3)); // 343, same as 7**3 
console.log(Math.pow(4, 0.5)); // 2, same as 4**0.5
console.log(Math.pow(7, -2)); // 0.02040816326530612,(1/49), same as 7**-2

3.ES8

  • async-await
  • Object.keys / values / entries
  • String padding: String.prototype.padStart / padEnd
  • Object.getOwnPropertyDescriptors

4.ES9

  • for await...of & Symbol.asyncIterator
  • Promise.prototype.finally
  • Object Rest Spread
    • the ability to use rest and spread operators on top of objects
    • let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
    • let spread = {...{x:1,y:2}}
  • RegExp Updates

1.for await...of

const asyncIterable = {
  [Symbol.asyncIterator]() {
    return {
      i: 0,
      next() {
        if (this.i < 3) {
          const self = this;
          return new Promise(function(resolve,reject){
                setTimeout(()=>{
                    resolve({ value: self.i++, done: false });
                  },1000*(self.i+1));
            });
        }else{
            console.log("final");
            return Promise.resolve({ value:"over",done: true });
        }
      }
    };
  }
};

(async function() {
   for await (let num of asyncIterable) {
     console.log(num);
   }
})();

5.ES10

  • JSON.stringify
  • Array.prototype.flat / flatMap
  • String.prototype.trimStart / trimEnd
  • String.prototype.matchAll
  • Object.fromEntries
  • Symbol.prototype.description
  • Function.prototype.toString
  • try...catch
  • BigInt
// MDN: var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) 
// {  return element for new_array }[, thisArg])
let arr1 = [1, 2, 3, 4];
arr1.map(x => [x * 2]); // [[2], [4], [6], [8]]
arr1.flatMap(x => [x * 2]); // [2, 4, 6, 8]
// only one level is flattened
arr1.flatMap(x => [[x * 2]]); // [[2], [4], [6], [8]]

// MDN: Object.fromEntries(iterable);
const obj = Object.fromEntries(new Map([
  ['foo', 'bar'],
  ['baz', 42]
]));

const obj2 = Object.fromEntries([ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]);

// Symbol.prototype.description
console.log(Symbol('desc').description); // "desc"
console.log(Symbol.iterator.description); // "Symbol.iterator"
console.log(Symbol.for('foo').description); // "foo"

// Function.prototype.toString()
function sum(a, b) {
  return a + b;
}
console.log(sum.toString());
// expected output: "function sum(a, b) {
//                     return a + b;
//                   }"