1656154562
Ecma 총회에서 승인한 ECMAScript 2022 / ES2022. 이 튜토리얼은 순전히 코드 샘플에서 JavaScript ES2022의 향상된 기능을 확인하는 데 도움이 될 것입니다.
Ecma 총회에서 승인한 ES2022. 13번째 에디션인 ECMAScript 2022는 top-level 을 도입 await
하여 키워드를 모듈의 최상위 수준에서 사용할 수 있게 했습니다. 새로운 클래스 요소: 공개 및 비공개 인스턴스 필드, 공개 및 비공개 정적 필드, 비공개 인스턴스 메서드 및 접근자, 비공개 정적 메서드 및 접근자 클래스 내부의 정적 블록, 클래스별 평가 초기화 수행 개체에 개인 필드가 있는지 테스트 하는 #x in obj
구문입니다. /d
일치하는 하위 문자열에 대한 시작 및 종료 인덱스를 제공 하는 플래그를 통한 정규식 일치 인덱스 ; 오류의 인과 관계를 기록하는 데 사용할 수 있는 개체 의 cause
속성 Error
상대 인덱싱을 허용 하는 at
Strings, Arrays 및 TypedArrays용 메서드. 그리고Object.hasOwn
, 편리한 대안 Object.prototype.hasOwnProperty
.
내장 인덱서블의 .at 메소드 📕 .
const cart = ['🍎', '🍌', '🍍'];
// first element
cart.at(0); // '🍎'
// last element
cart.at(-1); // '🍍'
// out of bounds
cart.at(-100); // undefined
cart.at(100); // undefined
const int8 = new Int8Array([0, 10, 42, -10]);
// first element
int8.at(0); // 0
// last element
int8.at(-1); // -10
// out of bounds
int8.at(-100) // undefined
int8.at(100) // undefined
const sentence = 'This is a sample sentence'
// first element
sentence.at(0); // 'T'
// last element
sentence.at(-1); // 'e'
// out of bounds
sentence.at(-100) // undefined
sentence.at(100) // undefined
캡처된 부분 문자열의 시작 및 끝 인덱스에 대한 추가 정보 📕
/(?<xs>x+)(?<ys>y+)/.exec('xxxyyxx');
/*[
'xxxyy',
'xxx',
'yy',
index: 0,
input: 'xxxyyxx',
groups: [Object: null prototype] { xs: 'xxx', ys: 'yy' }
]*/
let input = "abcd";
let match = /b(c)/.exec(input);
let indices = match.indices;
// `indices` has the same length as match
indices.length === match.length
// The first element of `indices` contains the start/end indices of the match
indices[0]; // [1, 3];
input.slice(indices[0][0], indices[0][1]); // same as match[0]
// The second element of `indices` contains the start/end indices of the first capture
indices[1]; // [2, 3];
input.slice(indices[1][0], indices[1][1]); // same as match[1]);
Object.hasOwn 📕
let books = {}
books.prop = 'exists';
// `hasOwn` will only return true for direct properties:
Object.hasOwn(books, 'prop'); // returns true
Object.hasOwn(books, 'toString'); // returns false
Object.hasOwn(books, 'hasOwnProperty'); // returns false
// The `in` operator will return true for direct or inherited properties:
'prop' in books; // returns true
'toString' in books; // returns true
'hasOwnProperty' in books; // returns true
오류의 원인을 나타내는 원인 속성입니다. 📕
const actual = new Error('a better error!', { cause: 'Error cause' });
actual instanceof Error; // true
actual.cause; // 'Error cause'
try {
maybeWorks();
} catch (err) {
throw new Error('maybeWorks failed!', { cause: err });
}
모듈의 비동기 함수 외부에서 기다 립니다 📕
// say this is index.mjs
// fails
await Promise.resolve('🍎');
// → SyntaxError: await is only valid in async function
// fix with wrapping
(async function() {
await Promise.resolve('🍎');
// → 🎉
}());
// to top-level await
await Promise.resolve('🍎') // '🍎'
const i18n = await import(`./content-${language}.mjs`);
공개 필드와 비공개 필드의 직교 정보 조합. 📕
class SampleClass {
/*
instead of:
constructor() { this.publicID = 42; }
*/
publicID = 42; // public field
/*
instead of:
static get staticPublicField() { return -1 }
*/
static staticPublicField = -1;
// static private field
static #staticPrivateField = 'private';
//private methods
#privateMethod() {}
// static block
static {
// executed when the class is created
}
}
예외 없이 브랜드 확인. 📕
class C {
#brand;
#method() {}
get #getter() {}
static isC(obj) {
// in keyword to check
return #brand in obj && #method in obj && #getter in obj;
}
}
#javascript #es2022 #es13
1656154562
Ecma 총회에서 승인한 ECMAScript 2022 / ES2022. 이 튜토리얼은 순전히 코드 샘플에서 JavaScript ES2022의 향상된 기능을 확인하는 데 도움이 될 것입니다.
Ecma 총회에서 승인한 ES2022. 13번째 에디션인 ECMAScript 2022는 top-level 을 도입 await
하여 키워드를 모듈의 최상위 수준에서 사용할 수 있게 했습니다. 새로운 클래스 요소: 공개 및 비공개 인스턴스 필드, 공개 및 비공개 정적 필드, 비공개 인스턴스 메서드 및 접근자, 비공개 정적 메서드 및 접근자 클래스 내부의 정적 블록, 클래스별 평가 초기화 수행 개체에 개인 필드가 있는지 테스트 하는 #x in obj
구문입니다. /d
일치하는 하위 문자열에 대한 시작 및 종료 인덱스를 제공 하는 플래그를 통한 정규식 일치 인덱스 ; 오류의 인과 관계를 기록하는 데 사용할 수 있는 개체 의 cause
속성 Error
상대 인덱싱을 허용 하는 at
Strings, Arrays 및 TypedArrays용 메서드. 그리고Object.hasOwn
, 편리한 대안 Object.prototype.hasOwnProperty
.
내장 인덱서블의 .at 메소드 📕 .
const cart = ['🍎', '🍌', '🍍'];
// first element
cart.at(0); // '🍎'
// last element
cart.at(-1); // '🍍'
// out of bounds
cart.at(-100); // undefined
cart.at(100); // undefined
const int8 = new Int8Array([0, 10, 42, -10]);
// first element
int8.at(0); // 0
// last element
int8.at(-1); // -10
// out of bounds
int8.at(-100) // undefined
int8.at(100) // undefined
const sentence = 'This is a sample sentence'
// first element
sentence.at(0); // 'T'
// last element
sentence.at(-1); // 'e'
// out of bounds
sentence.at(-100) // undefined
sentence.at(100) // undefined
캡처된 부분 문자열의 시작 및 끝 인덱스에 대한 추가 정보 📕
/(?<xs>x+)(?<ys>y+)/.exec('xxxyyxx');
/*[
'xxxyy',
'xxx',
'yy',
index: 0,
input: 'xxxyyxx',
groups: [Object: null prototype] { xs: 'xxx', ys: 'yy' }
]*/
let input = "abcd";
let match = /b(c)/.exec(input);
let indices = match.indices;
// `indices` has the same length as match
indices.length === match.length
// The first element of `indices` contains the start/end indices of the match
indices[0]; // [1, 3];
input.slice(indices[0][0], indices[0][1]); // same as match[0]
// The second element of `indices` contains the start/end indices of the first capture
indices[1]; // [2, 3];
input.slice(indices[1][0], indices[1][1]); // same as match[1]);
Object.hasOwn 📕
let books = {}
books.prop = 'exists';
// `hasOwn` will only return true for direct properties:
Object.hasOwn(books, 'prop'); // returns true
Object.hasOwn(books, 'toString'); // returns false
Object.hasOwn(books, 'hasOwnProperty'); // returns false
// The `in` operator will return true for direct or inherited properties:
'prop' in books; // returns true
'toString' in books; // returns true
'hasOwnProperty' in books; // returns true
오류의 원인을 나타내는 원인 속성입니다. 📕
const actual = new Error('a better error!', { cause: 'Error cause' });
actual instanceof Error; // true
actual.cause; // 'Error cause'
try {
maybeWorks();
} catch (err) {
throw new Error('maybeWorks failed!', { cause: err });
}
모듈의 비동기 함수 외부에서 기다 립니다 📕
// say this is index.mjs
// fails
await Promise.resolve('🍎');
// → SyntaxError: await is only valid in async function
// fix with wrapping
(async function() {
await Promise.resolve('🍎');
// → 🎉
}());
// to top-level await
await Promise.resolve('🍎') // '🍎'
const i18n = await import(`./content-${language}.mjs`);
공개 필드와 비공개 필드의 직교 정보 조합. 📕
class SampleClass {
/*
instead of:
constructor() { this.publicID = 42; }
*/
publicID = 42; // public field
/*
instead of:
static get staticPublicField() { return -1 }
*/
static staticPublicField = -1;
// static private field
static #staticPrivateField = 'private';
//private methods
#privateMethod() {}
// static block
static {
// executed when the class is created
}
}
예외 없이 브랜드 확인. 📕
class C {
#brand;
#method() {}
get #getter() {}
static isC(obj) {
// in keyword to check
return #brand in obj && #method in obj && #getter in obj;
}
}
#javascript #es2022 #es13
1656224640
经 Ecma 大会批准的 ECMAScript 2022 / ES2022。本教程将帮助您在代码示例中查看 JavaScript ES2022 的增强功能
ES2022 经 Ecma 大会批准。ECMAScript 2022 第 13 版引入了 top-level await
,允许在模块的顶层使用关键字;新的类元素:公共和私有实例字段、公共和私有静态字段、私有实例方法和访问器、私有静态方法和访问器;类内的静态块,用于执行每个类的评估初始化;#x in obj
语法,用于测试对象上是否存在私有字段;正则表达式通过/d
标志匹配索引,该标志为匹配的子字符串提供开始和结束索引;对象的cause
属性Error
,可用于记录错误的因果链;at
Strings、Arrays 和 TypedArrays的方法,它允许相对索引;和Object.hasOwn
,一个方便的替代方案Object.prototype.hasOwnProperty
。
.at内置可索引的方法📕。
const cart = ['🍎', '🍌', '🍍'];
// first element
cart.at(0); // '🍎'
// last element
cart.at(-1); // '🍍'
// out of bounds
cart.at(-100); // undefined
cart.at(100); // undefined
const int8 = new Int8Array([0, 10, 42, -10]);
// first element
int8.at(0); // 0
// last element
int8.at(-1); // -10
// out of bounds
int8.at(-100) // undefined
int8.at(100) // undefined
const sentence = 'This is a sample sentence'
// first element
sentence.at(0); // 'T'
// last element
sentence.at(-1); // 'e'
// out of bounds
sentence.at(-100) // undefined
sentence.at(100) // undefined
有关捕获的子字符串的开始和结束索引的附加信息📕
/(?<xs>x+)(?<ys>y+)/.exec('xxxyyxx');
/*[
'xxxyy',
'xxx',
'yy',
index: 0,
input: 'xxxyyxx',
groups: [Object: null prototype] { xs: 'xxx', ys: 'yy' }
]*/
let input = "abcd";
let match = /b(c)/.exec(input);
let indices = match.indices;
// `indices` has the same length as match
indices.length === match.length
// The first element of `indices` contains the start/end indices of the match
indices[0]; // [1, 3];
input.slice(indices[0][0], indices[0][1]); // same as match[0]
// The second element of `indices` contains the start/end indices of the first capture
indices[1]; // [2, 3];
input.slice(indices[1][0], indices[1][1]); // same as match[1]);
Object.hasOwn 📕
let books = {}
books.prop = 'exists';
// `hasOwn` will only return true for direct properties:
Object.hasOwn(books, 'prop'); // returns true
Object.hasOwn(books, 'toString'); // returns false
Object.hasOwn(books, 'hasOwnProperty'); // returns false
// The `in` operator will return true for direct or inherited properties:
'prop' in books; // returns true
'toString' in books; // returns true
'hasOwnProperty' in books; // returns true
Cause 属性指示错误的原因。📕
const actual = new Error('a better error!', { cause: 'Error cause' });
actual instanceof Error; // true
actual.cause; // 'Error cause'
try {
maybeWorks();
} catch (err) {
throw new Error('maybeWorks failed!', { cause: err });
}
在模块中的异步函数之外等待📕
// say this is index.mjs
// fails
await Promise.resolve('🍎');
// → SyntaxError: await is only valid in async function
// fix with wrapping
(async function() {
await Promise.resolve('🍎');
// → 🎉
}());
// to top-level await
await Promise.resolve('🍎') // '🍎'
const i18n = await import(`./content-${language}.mjs`);
公共和私有字段的正交信息组合。📕
class SampleClass {
/*
instead of:
constructor() { this.publicID = 42; }
*/
publicID = 42; // public field
/*
instead of:
static get staticPublicField() { return -1 }
*/
static staticPublicField = -1;
// static private field
static #staticPrivateField = 'private';
//private methods
#privateMethod() {}
// static block
static {
// executed when the class is created
}
}
品牌检查无一例外。📕
class C {
#brand;
#method() {}
get #getter() {}
static isC(obj) {
// in keyword to check
return #brand in obj && #method in obj && #getter in obj;
}
}
1656224400
ECMAScript 2022 / ES2022 tel qu'approuvé par l'Assemblée Générale Ecma. Ce didacticiel vous aidera à découvrir les améliorations de JavaScript ES2022 uniquement dans un exemple de code
ES2022 tel qu'approuvé par l'Assemblée générale de l'Ecma. ECMAScript 2022, la 13e édition, a introduit top-level await
, permettant au mot-clé d'être utilisé au niveau supérieur des modules ; nouveaux éléments de classe : champs d'instance publics et privés, champs statiques publics et privés, méthodes et accesseurs d'instance privés, et méthodes et accesseurs statiques privés ; blocs statiques à l'intérieur des classes, pour effectuer l'initialisation de l'évaluation par classe ; la #x in obj
syntaxe, pour tester la présence de champs privés sur les objets ; index de correspondance d'expression régulière via le /d
drapeau, qui fournit des indices de début et de fin pour les sous-chaînes correspondantes ; la cause
propriété sur les Error
objets, qui peut être utilisée pour enregistrer une chaîne de causalité dans les erreurs ; la at
méthode pour Strings, Arrays et TypedArrays, qui permet une indexation relative ; etObject.hasOwn
, une alternative pratique à Object.prototype.hasOwnProperty
.
Méthode .at sur les indexables intégrés 📕 .
const cart = ['🍎', '🍌', '🍍'];
// first element
cart.at(0); // '🍎'
// last element
cart.at(-1); // '🍍'
// out of bounds
cart.at(-100); // undefined
cart.at(100); // undefined
const int8 = new Int8Array([0, 10, 42, -10]);
// first element
int8.at(0); // 0
// last element
int8.at(-1); // -10
// out of bounds
int8.at(-100) // undefined
int8.at(100) // undefined
const sentence = 'This is a sample sentence'
// first element
sentence.at(0); // 'T'
// last element
sentence.at(-1); // 'e'
// out of bounds
sentence.at(-100) // undefined
sentence.at(100) // undefined
informations supplémentaires sur les indices de début et de fin des sous-chaînes capturées 📕
/(?<xs>x+)(?<ys>y+)/.exec('xxxyyxx');
/*[
'xxxyy',
'xxx',
'yy',
index: 0,
input: 'xxxyyxx',
groups: [Object: null prototype] { xs: 'xxx', ys: 'yy' }
]*/
let input = "abcd";
let match = /b(c)/.exec(input);
let indices = match.indices;
// `indices` has the same length as match
indices.length === match.length
// The first element of `indices` contains the start/end indices of the match
indices[0]; // [1, 3];
input.slice(indices[0][0], indices[0][1]); // same as match[0]
// The second element of `indices` contains the start/end indices of the first capture
indices[1]; // [2, 3];
input.slice(indices[1][0], indices[1][1]); // same as match[1]);
Objet.hasOwn 📕
let books = {}
books.prop = 'exists';
// `hasOwn` will only return true for direct properties:
Object.hasOwn(books, 'prop'); // returns true
Object.hasOwn(books, 'toString'); // returns false
Object.hasOwn(books, 'hasOwnProperty'); // returns false
// The `in` operator will return true for direct or inherited properties:
'prop' in books; // returns true
'toString' in books; // returns true
'hasOwnProperty' in books; // returns true
cause propriété indiquant la cause d'une erreur. 📕
const actual = new Error('a better error!', { cause: 'Error cause' });
actual instanceof Error; // true
actual.cause; // 'Error cause'
try {
maybeWorks();
} catch (err) {
throw new Error('maybeWorks failed!', { cause: err });
}
attendre en dehors des fonctions asynchrones dans les modules 📕
// say this is index.mjs
// fails
await Promise.resolve('🍎');
// → SyntaxError: await is only valid in async function
// fix with wrapping
(async function() {
await Promise.resolve('🍎');
// → 🎉
}());
// to top-level await
await Promise.resolve('🍎') // '🍎'
const i18n = await import(`./content-${language}.mjs`);
Combinaison orthogonale de champs publics et privés. 📕
class SampleClass {
/*
instead of:
constructor() { this.publicID = 42; }
*/
publicID = 42; // public field
/*
instead of:
static get staticPublicField() { return -1 }
*/
static staticPublicField = -1;
// static private field
static #staticPrivateField = 'private';
//private methods
#privateMethod() {}
// static block
static {
// executed when the class is created
}
}
Contrôles de marque sans exception. 📕
class C {
#brand;
#method() {}
get #getter() {}
static isC(obj) {
// in keyword to check
return #brand in obj && #method in obj && #getter in obj;
}
}
1656169026
ECMAScript 2022/ES2022, одобренный Генеральной Ассамблеей Ecma. Это руководство поможет вам ознакомиться с улучшениями JavaScript ES2022 исключительно в примере кода.
ES2022, одобренный Генеральной Ассамблеей Ecma. ECMAScript 2022, 13-я редакция, представила верхний уровень await
, позволяющий использовать ключевое слово на верхнем уровне модулей; новые элементы класса: общедоступные и частные поля экземпляра, общедоступные и частные статические поля, частные методы экземпляра и средства доступа, а также частные статические методы и средства доступа; статические блоки внутри классов для выполнения инициализации оценки для каждого класса; синтаксис для #x in obj
проверки наличия закрытых полей в объектах; индексы совпадения регулярных выражений с помощью /d
флага, который предоставляет начальные и конечные индексы для совпадающих подстрок; cause
свойство Error
объектов, которое можно использовать для записи причинно-следственной цепочки ошибок ; метод at
для строк, массивов и типизированных массивов, допускающий относительную индексацию; а такжеObject.hasOwn
, удобная альтернатива Object.prototype.hasOwnProperty
.
Метод .at для встроенных индексируемых объектов 📕 .
const cart = ['🍎', '🍌', '🍍'];
// first element
cart.at(0); // '🍎'
// last element
cart.at(-1); // '🍍'
// out of bounds
cart.at(-100); // undefined
cart.at(100); // undefined
const int8 = new Int8Array([0, 10, 42, -10]);
// first element
int8.at(0); // 0
// last element
int8.at(-1); // -10
// out of bounds
int8.at(-100) // undefined
int8.at(100) // undefined
const sentence = 'This is a sample sentence'
// first element
sentence.at(0); // 'T'
// last element
sentence.at(-1); // 'e'
// out of bounds
sentence.at(-100) // undefined
sentence.at(100) // undefined
дополнительная информация о начальных и конечных индексах захваченных подстрок 📕
/(?<xs>x+)(?<ys>y+)/.exec('xxxyyxx');
/*[
'xxxyy',
'xxx',
'yy',
index: 0,
input: 'xxxyyxx',
groups: [Object: null prototype] { xs: 'xxx', ys: 'yy' }
]*/
let input = "abcd";
let match = /b(c)/.exec(input);
let indices = match.indices;
// `indices` has the same length as match
indices.length === match.length
// The first element of `indices` contains the start/end indices of the match
indices[0]; // [1, 3];
input.slice(indices[0][0], indices[0][1]); // same as match[0]
// The second element of `indices` contains the start/end indices of the first capture
indices[1]; // [2, 3];
input.slice(indices[1][0], indices[1][1]); // same as match[1]);
Object.hasOwn 📕
let books = {}
books.prop = 'exists';
// `hasOwn` will only return true for direct properties:
Object.hasOwn(books, 'prop'); // returns true
Object.hasOwn(books, 'toString'); // returns false
Object.hasOwn(books, 'hasOwnProperty'); // returns false
// The `in` operator will return true for direct or inherited properties:
'prop' in books; // returns true
'toString' in books; // returns true
'hasOwnProperty' in books; // returns true
Свойство причины, указывающее причину ошибки. 📕
const actual = new Error('a better error!', { cause: 'Error cause' });
actual instanceof Error; // true
actual.cause; // 'Error cause'
try {
maybeWorks();
} catch (err) {
throw new Error('maybeWorks failed!', { cause: err });
}
await вне асинхронных функций в модулях 📕
// say this is index.mjs
// fails
await Promise.resolve('🍎');
// → SyntaxError: await is only valid in async function
// fix with wrapping
(async function() {
await Promise.resolve('🍎');
// → 🎉
}());
// to top-level await
await Promise.resolve('🍎') // '🍎'
const i18n = await import(`./content-${language}.mjs`);
Ортогонально-информированная комбинация открытых и частных полей. 📕
class SampleClass {
/*
instead of:
constructor() { this.publicID = 42; }
*/
publicID = 42; // public field
/*
instead of:
static get staticPublicField() { return -1 }
*/
static staticPublicField = -1;
// static private field
static #staticPrivateField = 'private';
//private methods
#privateMethod() {}
// static block
static {
// executed when the class is created
}
}
Проверка брендов без исключений. 📕
class C {
#brand;
#method() {}
get #getter() {}
static isC(obj) {
// in keyword to check
return #brand in obj && #method in obj && #getter in obj;
}
}
#javascript #es2022 #es13
1656224520
ECMAScript 2022 / ES2022 conforme aprovado pela Assembleia Geral da Ecma. Este tutorial ajudará você a verificar os aprimoramentos do JavaScript ES2022 puramente no exemplo de código
ES2022 conforme aprovado pela Assembleia Geral da Ecma. ECMAScript 2022, a 13ª edição, introduziu o nível superior await
, permitindo que a palavra-chave seja usada no nível superior dos módulos; novos elementos de classe: campos de instância pública e privada, campos estáticos públicos e privados, métodos e acessadores de instância privada e métodos e acessadores estáticos privados; blocos estáticos dentro de classes, para realizar a inicialização de avaliação por classe; a #x in obj
sintaxe, para testar a presença de campos privados em objetos; índices de correspondência de expressões regulares por meio do /d
sinalizador, que fornece índices de início e fim para substrings correspondentes; a cause
propriedade em Error
objetos, que pode ser usada para registrar uma cadeia de causalidade em erros; o at
método para Strings, Arrays e TypedArrays, que permite a indexação relativa; eObject.hasOwn
, uma alternativa conveniente para Object.prototype.hasOwnProperty
.
.at em indexáveis integrados 📕 .
const cart = ['🍎', '🍌', '🍍'];
// first element
cart.at(0); // '🍎'
// last element
cart.at(-1); // '🍍'
// out of bounds
cart.at(-100); // undefined
cart.at(100); // undefined
const int8 = new Int8Array([0, 10, 42, -10]);
// first element
int8.at(0); // 0
// last element
int8.at(-1); // -10
// out of bounds
int8.at(-100) // undefined
int8.at(100) // undefined
const sentence = 'This is a sample sentence'
// first element
sentence.at(0); // 'T'
// last element
sentence.at(-1); // 'e'
// out of bounds
sentence.at(-100) // undefined
sentence.at(100) // undefined
informações adicionais sobre os índices inicial e final das substrings capturadas 📕
/(?<xs>x+)(?<ys>y+)/.exec('xxxyyxx');
/*[
'xxxyy',
'xxx',
'yy',
index: 0,
input: 'xxxyyxx',
groups: [Object: null prototype] { xs: 'xxx', ys: 'yy' }
]*/
let input = "abcd";
let match = /b(c)/.exec(input);
let indices = match.indices;
// `indices` has the same length as match
indices.length === match.length
// The first element of `indices` contains the start/end indices of the match
indices[0]; // [1, 3];
input.slice(indices[0][0], indices[0][1]); // same as match[0]
// The second element of `indices` contains the start/end indices of the first capture
indices[1]; // [2, 3];
input.slice(indices[1][0], indices[1][1]); // same as match[1]);
Object.hasOwn 📕
let books = {}
books.prop = 'exists';
// `hasOwn` will only return true for direct properties:
Object.hasOwn(books, 'prop'); // returns true
Object.hasOwn(books, 'toString'); // returns false
Object.hasOwn(books, 'hasOwnProperty'); // returns false
// The `in` operator will return true for direct or inherited properties:
'prop' in books; // returns true
'toString' in books; // returns true
'hasOwnProperty' in books; // returns true
cause propriedade que indica a causa de um erro. 📕
const actual = new Error('a better error!', { cause: 'Error cause' });
actual instanceof Error; // true
actual.cause; // 'Error cause'
try {
maybeWorks();
} catch (err) {
throw new Error('maybeWorks failed!', { cause: err });
}
aguarde fora das funções assíncronas nos módulos 📕
// say this is index.mjs
// fails
await Promise.resolve('🍎');
// → SyntaxError: await is only valid in async function
// fix with wrapping
(async function() {
await Promise.resolve('🍎');
// → 🎉
}());
// to top-level await
await Promise.resolve('🍎') // '🍎'
const i18n = await import(`./content-${language}.mjs`);
Combinação informada ortogonalmente de campos públicos e privados. 📕
class SampleClass {
/*
instead of:
constructor() { this.publicID = 42; }
*/
publicID = 42; // public field
/*
instead of:
static get staticPublicField() { return -1 }
*/
static staticPublicField = -1;
// static private field
static #staticPrivateField = 'private';
//private methods
#privateMethod() {}
// static block
static {
// executed when the class is created
}
}
Verificações de marca sem exceções. 📕
class C {
#brand;
#method() {}
get #getter() {}
static isC(obj) {
// in keyword to check
return #brand in obj && #method in obj && #getter in obj;
}
}