ES 11 여러 번 시도 해 보 았 지만 불쾌 한 새로운 특성 을 몇 가지 사 용 했 습 니 다.
특성 쟁탈 선지 자:
사유 변수
내부 에서 사용 할 Class 변 수 를 엄 격 히 제한 합 니 다.변수 앞 에\#만 추가 하면 개인 변수 가 될 수 있 고 class 외부 에서 직접 접근 할 수 없습니다.
다음은 저희 가 간단 한 걸 로...
class Hero {
  #aggressivity = 0
  constructor (aggressivity){
   this.#aggressivity = aggressivity
  }
  getHurt(){
   return this.#aggressivity
  }
  setAggressivity(aggressivity){
   this.#aggressivity = aggressivity
  }
}
const shooter = new Hero(100)
let hurt = shooter.getHurt()
console.log(hurt) //100
console.log(shooter.#aggressivity) //Error : Uncaught SyntaxError: Private field '#aggressivity' must be declared in an enclosing class클 라 스 를 통 해서 만 접근 할 수 있 으 며,클 라 스 를 통일 하 는 공공 방법 을 통 해 통일 적 으로 수정 할 수 있 습 니 다.
현재 사수 가 광폭 스 킬 을 가지 고 10%데 미 지 를 증가 시 켰 다 고 가정 하면 setAggressivity 를 통 해 공 격 력 을 수정 할 수 있 습 니 다.
 
 
let aggressivity = parseInt(hurt * 1.1)
shooter.setAggressivity(aggressivity)
console.log(shooter.getHurt()) // 110이 새로운 특성 에 대해 이야기 하기 전에 Promise.all 과 Promise.race 를 간단히 살 펴 보고 왜 Promise.allSettled 라 는 새로운 특성 이 필요 한 지 추측 해 보 자.
Promise.all:여러 Promise 인 스 턴 스 를 새로운 Promise 인 스 턴 스 로 포장 할 수 있 습 니 다.또한 성공 과 실패 의 반환 값 은 다 릅 니 다.성공 할 때 는 결과 배열 을 되 돌려 주 고 실패 할 때 는 가장 먼저 reject 실패 상태의 값 을 되 돌려 줍 니 다.
let p1 = new Promise((resolve, reject) => {
 resolve('   ')
})
let p2 = new Promise((resolve, reject) => {
 resolve('success')
})
let p3 = Promse.reject('  ')
Promise.all([p1, p2]).then((result) => {
 console.log(result) //['   ', 'success']
}).catch((error) => {
 console.log(error)
})
Promise.all([p1,p3,p2]).then((result) => {
 console.log(result)
}).catch((error) => {
 console.log(error) //    ,   '  '
})
const promise1 = new Promise((resolve, reject) => {
 setTimeout(resolve, 500, 'one');
});
const promise2 = new Promise((resolve, reject) => {
 setTimeout(resolve, 100, 'two');
});
Promise.race([promise1, promise2]).then((value) => {
 console.log(value);
});
//   "two"   promise2     promise1 
let allSettled = (funcArr) => {
 return new Promise((resolve) => {
  let sttled = 0
  let result = []
  for(let index = 0;index<funcArr.length;index++){
   const element = funcArr[index]
   element
   .then(res => { 
    result[index] = {
     status: 'fulfilled',
     value: res
    }
   })
   .catch(err => { 
    result[index] = {
     status: 'rejected',
     reason: err
    }
   })
   .finally(() => { ++sttled === funcArr.length && resolve(result) })
  }
 })
}
//  
const promises = [
  Promise.reject('c'),
  Promise.resolve('a'),
  Promise.resolve('b'),
];
allSettled(promises).then(res => {
  console.log(res)
})
//     
// [{"status":"rejected","reason":"c"},
// {"status":"fulfilled","value":"a"},
// {"status":"fulfilled","value":"b"}]
const promises = [
  Promise.reject('c'),
  Promise.resolve('a'),
  Promise.resolve('b'),
];
Promise.allSettled(promises).then(res =>{
 console.log(res)
})
//     
// [{"status":"rejected","reason":"c"},
// {"status":"fulfilled","value":"a"},
// {"status":"fulfilled","value":"b"}]상태 가 fulfilled 일 때 성공 을 의미 하고 하나의 value 를 포함 하 며 성공 의 결 과 를 의미 합 니 다.
상태 가 rejected 일 때 실 패 를 대표 하고 reason 을 포함 하 며 실패 의 원인 을 대표 합 니 다.
BigInt
JS 에 명시 적 정수 유형 이 부족 한 것 은 종종 당 혹 스 럽 다.많은 프로 그래 밍 언어 는 부동 소수점 형,이중 정밀도 형,정수 형,이중 정밀도 형 등 여러 가지 디지털 유형 을 지원 하지만 JS 는 그렇지 않다.JS 에서 IEEE 754-2008 표준 의 정의 에 따라 모든 숫자 는 이중 정밀도 64 비트 부동 소수점 형식 으로 표시 된다.
이 기준 에서 정확하게 표시 할 수 없 는 매우 큰 정 수 는 자동 으로 반올림 된다.정확히 말 하면 JS 의 Number 유형 은-9007199254740991(-(2^53-1)만 안전하게 표시 할 수 있 습 니 다. 9007199254740991(2^53-1)과 의 정 수 는 이 범 위 를 초과 한 모든 정수 가 정 도 를 잃 을 수 있 습 니 다.
console.log(9999999999999999);  //10000000000000000
//          
const A = Number.MAX_SAFE_INTEGER + 1
const B = Number.MAX_SAFE_INTEGER + 2
console.log(Number.MAX_SAFE_INTEGER) //9007199254740991
console.log(A) //9007199254740992
console.log(B) //9007199254740992
console.log(A === B) //trueBigInt 가 하늘 로 나 와 표준 JS 에서 큰 정수 에 대한 산술 연산 을 수행 할 수 있 으 므 로 정밀도 손실 위험 을 걱정 하지 않 아 도 됩 니 다.
BigInt 데이터 형식 을 만 드 는 방법 은 매우 간단 합 니 다.정수 뒤에 n 을 추가 하거나 BigInt()를 통 해 인 스 턴 스 를 만 들 수 있 습 니 다.
const bigint = 999999999999999999n
const bigintByMethod = BigInt('999999999999999999')
console.log(bigint) //999999999999999999n
console.log(bigintByMethod) //999999999999999999n
console.log(bigint === bigintByMethod) //true
//   
console.log(BigInt(true)) //1n
console.log(BigInt(false)) //0n
console.log(typeof bigint) //"bigint" 
console.log(88n == 88) //true
console.log(88n === 88) //false
console.log(88n+1) //Error =>Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
console.log(1n + 2n) //3n
console.log(1n - 2n) //-1n
console.log(+ 1n) //Uncaught TypeError: Cannot convert a BigInt value to a number
console.log(- 1n) //-1n
console.log(10n * 20n) //200n
console.log(23n%10n) //3n
console.log(20n/10n) //2n
......
console.log(25n / 10n) //2n
console.log(29n / 10n) //2n
if (5n) {
  //          
}
if (0n) {
  //          
}논리 연산 자 추가??,처리 null 과 undefined,작업 원 리 는 논리 or(||)와 유사 하지만 이와 반대 입 니 다.
||진실 을 위해 왼쪽 값 을 되 돌려 주지 않 으 면 오른쪽 으로 돌아 갑 니 다.
0 || 5 // return 5
"" || 5 // return 5
"     " || 'V5' //return "     "
0 ?? 5 //return 0
"" ?? 5 //return ""
null ?? 5 // return 5
undefined ?? 5 // return 5
false ?? 5 //return false
NaN ?? 5 // return NaN
"     " || undefined ?? "Sneaker" //Uncaught SyntaxError: Unexpected token '??'
"     " && undefined ?? "Sneaker" //Uncaught SyntaxError: Unexpected token '??'
("     " || undefined) ?? "(๑•̀ㅂ•́)و✧" //"     "
("     " && null) ?? "    " //"    "일상적인 개발 에서 많은 개발 자 들 이 Cannot read property XXX of undefined 를 만 나 정의 되 지 않 은 데이터 에서 필드 를 읽 을 수 없습니다.
선택 가능 한 체인 연산 자 는 끼 워 넣 은 대상 을 찾 을 때 체인 의 첫 번 째 undefined 나 null 을 찾 으 면 즉시 종료 되 고 undefined 로 되 돌아 갑 니 다.계속 아래로 찾 아 잘못 던 지지 않 습 니 다.
const obj = {
 foo: {
  bar: {
   baz: 42,
  },
 },
}
console.log(obj.fo.bar.baz) //Uncaught TypeError: Cannot read property 'bar' of undefined
         ,                   ,     
if(obj&&obj.foo&&obj.foo.bar){
 console.log(obj.foo.bar.baz) // 42
}
console.log(obj?.foo?.bar?.baz) //42
      
console.log(obj.foo.bar?.baz) //42표준 import 가 져 오기 에 서 는 정적 으로 가 져 옵 니 다.가 져 온 모든 모듈 은 불 러 올 때 컴 파일 되 어 필요 에 따라 컴 파일 할 수 없습니다.조건 이 필요 할 때 require()만 사용 할 수 있 습 니 다.
그러나 이 제 는 이러한 상황 을 개선 할 방법 이 있 습 니 다.동적 가 져 오기 가 코드 를 사용 하지 않 은 컴 파일 을 효과적으로 줄 이 고 첫 화면 로 딩 속 도 를 높 일 수 있 으 며 필요 에 따라 로 딩 할 수 있 기 때 문 입 니 다.
그렇다면 왜 우 리 는 동적 가 져 오기 가 필요 합 니까?
4
//      
import("/module/sneaker/test.js")
.then(module => {
 //      
})
//await
const getModule = await import("/module/sneaker/test.js")
//  async await
const getUserInfo = async (hasLogin) => {
 if(!hasLogin){
 const user = await import("/module/sneaker/user.js")
  user.getInfo()
 }
}String 프로 토 타 입 에 있 는 새로운 방법 을 기반 으로 문자열 과 정규 표현 식 을 일치 시 킬 수 있 습 니 다.반환 값 은 모든 결과 와 일치 하 는 교체 기 입 니 다.
for...of 를 통 해 옮 겨 다 니 거나 연산 자...,Array.from 을 통 해 결과 교체 기 를 배열 로 변환 할 수 있 습 니 다.
const string = 'Hello Sneaker,Where is the library?'
const regex = /[A-W]/g
const matches = string.matchAll(regex)
console.log(...matches)
//["H", index: 0, input: "Hello Sneaker,Where is the library?", groups: undefined] 
//["S", index: 6, input: "Hello Sneaker,Where is the library?", groups: undefined] 
//["W", index: 14, input: "Hello Sneaker,Where is the library?", groups: undefined] 전역 대상 을 방문 하 는 표준 방법 을 제공 하기 위해 서다.
브 라 우 저 에 서 는 window/self/frames 를 사용 하여 전체 대상 을 방문 할 수 있 지만,웹 Workers 에 서 는 self 만 사용 할 수 있 고,Node 에 서 는 완전히 다 르 기 때문에 global 을 사용 해 야 합 니 다.
globalThis 가 표준 이 되 기 전에 전체 대상 을 얻 으 려 면 이렇게 해 야 할 수도 있 습 니 다.
const globalObj = (()=>{
 if(self) return self
 if(window) return window
 if(global) return global
 throw new Error('Sorry!No global obj found')
})
//Browser 
globalThis === window //true
//Webworker
globalThis === self //true
//Node
globalThis === global //trueModule Namespace Exports 특정 네 임 스페이스 가 져 오기
export * as ns from './module
//   
import * as ns from './module'
export {ns}레 퍼 런 스
특성 이 많 지만 어떤 것 은 재 미 있 습 니 다.예 를 들 어 체인 과 빈 자 리 를 합 쳐 연산 자 를 선택 할 수 있 습 니 다.여러 번 시도 해 보 았 지만 얼마나 시원 한 지 알 수 있 습 니 다.새로운 특성 은 평소에 쓰 지 않 아 도 잊 혀 지기 쉬 우 므 로 평소에 의식 적 으로 자주 회고 하고 활용 하 며 함께 공부 하고 성장 하 는 것 을 권장 합 니 다.
ES 11 의 여러 번 시도 되 고 불쾌 한 새로운 특성 에 관 한 이 글 은 몇 개의 글 을 사용 하여 여기까지 소개 하 였 습 니 다.더 많은 ES 11 의 새로운 특성 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
ES6 / ES11 기능 정리ECMA라는 국제 기구에서 만든 표준문서인 ECMAScript(=ES)의 6번째 개정판 문서에 있는 표준 스펙을 말한다. 2015년에 출시된 ES6가 다른 ES 시리즈에 비해 가장 많이 불리는 이유는 이 때의 자바스...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.