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

283
Visualizações
Javascript new keyword difference in output

Why do I get 2 different output when I run in Chrome -> DevTools -> Sources and when I run in JSFiddle.

The code which I run is as follows

function foo() {
    this.baz = "baz"
    console.log(this.bar + " " + baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)

Output in chrome

undefined [object Object]
baz

Output in JSFiddle

"undefined undefined"
"baz"

Essentially chrome is telling me that baz is an object of type {baz:"baz"} but jsFiddle tells me it is undefined.

enter image description here enter image description here

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

0

Are you sure you did not run the same code on chrome twice?

The first time baz is clearly undefined, but if you paste the same code again it has the value you already defined (var baz = new foo();).

about 4 years ago · Juan Pablo Isaza Relatório

0

When a standard page with that code on it is run the result is undefined undefined and then baz.

Inside the function, baz refers to the outer variable named baz, which is the instance that's being created (but hasn't been created yet - it'll be created after the foo function returns the instance). So, at that moment, it should be undefined.

But, the console is not like a standard webpage; it'll save previous values assigned to variables when you run it again. You must have run the code more than once - in which case, it's like doing

function foo() {
    this.baz = "baz"
    console.log(this.bar + " " + baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)

// you probably cleared the console manually at this point
// before running it again

function foo() {
    this.baz = "baz"
    console.log(this.bar + " " + baz);
}

var bar = "bar";
var baz = new foo();
console.log(baz.baz)

so the [object Object] you see is from a previous run's instance.

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