ES2020

Syntax

Class Private Variables

class Person {
	#age
	
	constructor(firstName, lastName, age) {
    this.firstName = firstName
    this.lastName = lastName
    this.#age = age
  }
}

const youcheng = new Person('YouCheng', 'hsu', 30)
console.log(youcheng.#age) //Private field '#age' must be declared in an enclosing class

Nullish Coalescing Operator

const youcheng = {
  firstName: 'YouCheng',
  lastName: ''
  age: 0
}

console.log(youcheng.firstName ?? 'YOU CHENG') //youCheng
console.log(youcheng.lastName ?? 'Hsu') //''
console.log(youcheng.age ?? 30) //0
console.log(youcheng.city ?? 'hsinchu') //hsinchu

Optional Chaining Operator

const youcheng = {
  sibling: {
    sister: 'vivien'
  }
}

console.log(youcheng?.sibling?.sister) //vivien
console.log(youcheng?.sibling?.brother) //undefined
console.log(youcheng?.parents?.father) //undefined

API

String.prototype.matchAll

const test = "climbing, oranges, jumping, flying, carrot";
const regex = /([a-z]*)ing/g;
const matches = Array.from(test.matchAll(regex));
const result = matches.map(match => match[1]);

console.log(result) //['climb', 'jump', 'fly']

import()

import('@/utils').then(utils => {
  console.log(utils.isSame(1, 1))
})

BigInt

  • 數字尾端加個 n, 即為 BigInt
  • BigInt(0) 即為 BigInt
  • BigInt 不可與 Number 進行運算
  • BigInt 不可使用 Math API 進行運算
  • BigInt 不為 BigDecimal, 進行除法時 Decimal 無條件捨去
    • 其他細節參考 MDN
BigInt(Number.MAX_SAFE_INTEGER) + 2n //9007199254740996n
Number.MAX_SAFE_INTEGER + 2 //TypeError: can't convert BigInt to number

Promise.allSettled

enum PromiseStatus {
  FULFILLED = 'fulfilled',
  REJECTED = 'rejected'
}

interface FulfillResult<R = any> {
  status: PromiseStatus.FULFILLED
  value: R
}

interface RejectResult<R = any> {
  status: PromiseStatus.REJECTED
  reason: R
}

declare Promise {
  function allSettled(...args: Promise[]): Promise<(FulfillResult | RejectResult)[]>
}

globalThis

console.log(globalThis === window) //true

globalThis.youcheng = {}
console.log(globalThis.youcheng === window.youcheng) //true

import.meta

可以使用 import.meta 存取類似 nodejs 中的 __dirname, __filename

__dirname 為例:

import(new URL('./static/js/home.js', import.meta.url))