Novos recursos do ES2021 / ES12

Espera-se que a versão 2021 do ECMAScript seja lançada em junho de 2021. Aqui estão alguns dos recursos que você pode encontrar no ES2021 ou ES12. A lista é baseada em propostas ECMAScript e novos recursos lançados pelo motor Google Chrome V8.





Todos os recursos listados abaixo são suportados no momento da escrita no Google Chrome Canary build (a versão experimental do navegador Google Chrome).





Método string replaceAll ()

String.prototype.replaceAll () substitui todas as ocorrências de uma string por um valor de string diferente.





Atualmente em JavaScript, as strings têm um método replace (). Ele pode ser usado para substituir uma substring por outra string.





const str = "Backbencher sits at the Back";
const newStr = str.replace("Back", "Front");
console.log(newStr); // "Frontbencher sits at the Back"
      
      



Se o padrão de substituição de entrada for uma string, o método replace () substitui apenas a primeira ocorrência. Portanto, o código não substitui a segunda ocorrência de " Voltar ".





Só podemos fazer uma substituição completa se fornecermos o padrão de substituição como uma expressão 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 () tenta substituir todas as ocorrências, mesmo se o padrão de entrada for uma string .





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
      
      



Na linha 2, se a for nulo ou indefinido , o lado direito ?? é avaliado e atribuído a b .





Vamos agora considerar ?? junto com = .





let x;
let y = 2;
x ??= y;
console.log(x); // 2
      
      



A linha 2 no código acima é equivalente à seguinte expressão:





x = x ?? (x = y)
      
      



Aqui x é indefinido . Portanto, a expressão à direita é avaliada e define x como 2 .








All Articles