Tarefa JS curta para segunda-feira

imagem

Que nasceu no processo de estudar os pesadelos do LexicalEnvironment e o programa geralmente educacional sobre o tema "Por que funciona assim?"


A tarefa realmente veio da série wtfjs, mas após uma análise cuidadosa, ela se encaixa completamente na lógica da linguagem.


Então, direto ao ponto:


Existe um módulo module.js :


 // module.js function getRandomNumber() { return Math.floor(Math.random() * 100) } var a = 10; function b() { a = 100; return; function a() {} } b(); module.exports = getModule(); async function getModule() { return { a, get getterA() { return a }, x: ++a + ++a, rndA: a + getRandomNumber(), getA: function() { return this.a }, getArrowA: () => this.a, getRndA: () => a + getRandomNumber() } } 

É chamado do arquivo index.js:


 // index.js a = 5; (async () => { let moduleObj1 = await require("./module") let moduleObj2 = await require("./module") console.log( ` ============================ m1Obj.a: | ${moduleObj1.a} m1Obj.getterA: | ${moduleObj1.getterA} m1Obj.x: | ${moduleObj1.x} m1Obj.getA: | ${moduleObj1.getA()} m1Obj.getArrowA: | ${moduleObj1.getArrowA()} m1Obj.rndA: | ${moduleObj1.rndA} m1Obj.getRndA: | ${moduleObj1.getRndA()} ============================ m2Obj.a: | ${moduleObj2.a} m2Obj.getterA: | ${moduleObj2.getterA} m2Obj.x: | ${moduleObj2.x} m2Obj.getA: | ${moduleObj2.getA()} m2Obj.getArrowA: | ${moduleObj2.getArrowA()} m2Obj.rndA: | ${moduleObj2.rndA} m2Obj.getRndA: | ${moduleObj2.getRndA()} ============================ a: | ${a} ============================` ) })() 

Na verdade, a pergunta é: o que será exibido no console?


A resposta é:
  ============================ m1Obj.a: | 10 m1Obj.getterA: | 12 m1Obj.x: | 23 m1Obj.getA: | 10 m1Obj.getArrowA: | 5 m1Obj.rndA: |    12  111 m1Obj.getRndA: |    12  111 ============================ m2Obj.a: | 10 m2Obj.getterA: | 12 m2Obj.x: | 23 m2Obj.getA: | 10 m2Obj.getArrowA: | 5 m2Obj.rndA: |    12  111 m2Obj.getRndA: |    12  111 ============================ a: | 5 ============================ 

Source: https://habr.com/ru/post/pt456436/


All Articles