Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
Does the change of object in js is also local in a function?

The bellow generates a file containing code and prints the output of the program:

 class Code {
  static list = require("./settings.json");
  static fs = require("fs");
  constructor(
    code="print('Hello World')",//default code
    lang = "py",//language
    fn = "test",//file name
    args = "" //arguments
  ) {
    this.code = code;
    const path = require('path');
    this.fn = path.join(__dirname,fn) + "." + lang;//for platform independence
    this.run_com = Code.replace(Code.list[lang], this.fn, args);
    this._output="Server not responding";
              this._error="Server not responding";
  }

  file_exists()
  {
    return Code.fs.existsSync(`${this.fn}`);
  }

  make_file() {
    Code.fs.writeFile(`${this.fn}`, this.code, (err) => {
      if (err) {
        console.log(err);
      }
    });
  }

  run_file()
  {
      if(!this.file_exists())
      this.make_file();

      const { exec } = require("child_process");
      
      exec(this.run_com, (error, stdout, stderr) =>{
          if(error)
          {
              console.log(error);
          }
          
          else if(stderr==""){
          this._output=stdout;
          this._error="No error";
      }

          else{
          this._error=stderr;
          this._output=stdout;
          }
          console.log(this);//this
        });
        console.log(this);//this
  }

  get error()
  {
      return this._error;
  }

  get output()
  {
      return this._output;
  }

  static replace(
    s //replace {}
  ) {
    const arg = Object.values(arguments).slice(1); //convert obj to array removing s
    for (let i in arg) {
      s = s.replace("{}", arg[i]);
    }
    return s;
  }
}

a = new Code("print('exd')");
a.run_file();

In the above program the output is: enter image description here

The change in the state of object is not persistent once it comes out of the inner function.

why does the second console.log prints first and why the output of both the console.log are different, please justify in detail.

Also suggest a solution of this problem.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think this is because exec is async and the second log is printed first. When the async code executes the second log is printed. And in the exec the values of _output and _error are changed hence the difference.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda