Se espera que ECMAScript versión 2021 se lance en junio de 2021. Estas son algunas de las características que puede encontrar en ES2021 o ES12. La lista se basa en las propuestas de ECMAScript y las nuevas funciones lanzadas por el motor Google Chrome V8.
Todas las funciones enumeradas a continuación son compatibles en el momento de escribir este artículo en la compilación de Google Chrome Canary (la versión experimental del navegador Google Chrome).
Método string replaceAll ()
String.prototype.replaceAll () reemplaza todas las apariciones de una cadena con un valor de cadena diferente.
Actualmente en JavaScript, las cadenas tienen un método replace (). Se puede utilizar para reemplazar una subcadena con otra cadena.
const str = "Backbencher sits at the Back";
const newStr = str.replace("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Back"
Si el patrón de reemplazo de entrada es una cadena, el método replace () reemplaza solo la primera aparición. Por lo tanto, el código no reemplaza la segunda aparición de " Atrás ".
Solo podemos hacer un reemplazo completo si proporcionamos el patrón de reemplazo como una expresión regular .
const str = "Backbencher sits at the Back";
const newStr = str.replace(/Back/g, "Front");
console.log(newStr); // "Frontbencher sits at the Front"
String.prototype.replaceAll () intenta reemplazar todas las ocurrencias, incluso si el patrón de entrada es una cadena .
const str = "Backbencher sits at the Back";
const newStr = str.replaceAll("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Front"
Métodos privados
, . #.
class Person {
//
#setType() {
console.log("I am Private");
}
//
show() {
this.#setType();
}
}
const personObj = new Person();
personObj.show(); // "I am Private";
personObj.setType(); // TypeError: personObj.setType is not a function
setType() , personObj.setType undefined. undefined TypeError.
- (get/set) , # .
class Person {
//
get name() { return "Backbencher" }
set name(value) {}
//
get #age() { return 42 }
set #age(value) {}
}
get set name . , name , .
const obj = new Person();
console.log(obj.name); // "Backbencher"
console.log(obj.age); // undefined
WeakRef
WeakRef (Weak References). . , . , , , .
JavaScript - . , JavaScript . JavaScript , MDN.
:
const callback = () => {
const aBigObj = {
name: "Backbencher"
};
console.log(aBigObj);
};
(async function(){
await new Promise((resolve) => {
setTimeout(() => {
callback();
resolve();
}, 2000);
});
})();
. callback() setTimeout(). await. await - ES6, .
2 «Backbencher». , callback(), aBigObj .
aBigObj .
const callback = () => {
const aBigObj = new WeakRef({
name: "Backbencher"
});
console.log(aBigObj.deref().name);
}
(async function(){
await new Promise((resolve) => {
setTimeout(() => {
callback(); // "Backbencher"
resolve();
}, 2000);
});
await new Promise((resolve) => {
setTimeout(() => {
callback(); // , "Backbencher"
resolve();
}, 5000);
});
})();
WeakRef new WeakRef(). .deref(). setTimeout() name. .
, setTimeout() «Backbencher». . -, . WeakRef , .
FinalizationRegistry - WeakRef. , , .
const registry = new FinalizationRegistry((value) => {
console.log(value);
});
registry FinalizationRegistry. (), FinalizationRegistry, .
(function () {
const obj = {};
registry.register(obj, "Backbencher");
})();
3 obj registry. obj , .register() . , , obj , «Backbencher» .
Google Chrome Canary, 1 , «Backbencher» . Chrome - « ». «».
Promise.any() AggregateError
Promise.any() , . 3 , .
const p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("A"), Math.floor(Math.random() * 1000));
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve("B"), Math.floor(Math.random() * 1000));
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve("C"), Math.floor(Math.random() * 1000));
});
Promise.any() p1, p2 p3.
(async function() {
const result = await Promise.any([p1, p2, p3]);
console.log(result); // "A", "B" "C"
})();
, ? Promise.any() AggregateError. .
const p = new Promise((resolve, reject) => reject());
try {
(async function() {
const result = await Promise.any([p]);
console.log(result);
})();
} catch(error) {
console.log(error.errors);
}
Promise.any() . « » (reject). .
(&&, || ??) .
let x = 1;
let y = 2;
x &&= y;
console.log(x); // 2
3 :
x && (x = y)
-:
if(x) {
x = y
}
x - , y, 2.
&&, || ??.
||
.
let x = 1;
let y = 2;
x ||= y;
console.log(x); // 1
3 :
x || (x = y)
, , x . x 1, , , , . 1 .
??
?? - (Nullish Coalescing operator) JavaScript. , , null undefined , . null undefined, .
let a;
let b = a ?? 5;
console.log(b); // 5
En la línea 2, si el valor de a es nulo o indefinido , ¿el lado derecho ? es evaluado y asignado a b .
Consideremos ahora ?? junto con = .
let x;
let y = 2;
x ??= y;
console.log(x); // 2
La línea 2 del código anterior es equivalente a la siguiente expresión:
x = x ?? (x = y)
Aquí x no está definido . Entonces, la expresión de la derecha se evalúa y establece x en 2 .