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

208
Visualizações
Why is Object constructors property globally scoped?

Given the following:

function MyClass() {
  this.name = "Agnus"

  return function() {
    console.log(this.name)
  }
}


const user = new MyClass() //this = "MyClass"
const r = MyClass() //this = "window"

console.log(name) //Agnus, this = "window"
r() //Agnus, this = "window"

My expectation was that on calling r(), I will get a error as the value of "this" is window for its case but instead it returned me "Agnus". On checking, I found that the properties of the object constructor MyClass are available from global.

enter image description here

I am having little difficulty to wrap my mind around such behavior, so it will be really nice if someone can explain me a bit about this.

Thank you for your help.

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

0

When you use new, you set the this to a new empty object whose internal prototype is the constructor's .prototype. That is:

new MyClass()
function MyClass() {
  // `this` is now equivalent to Object.create(MyClass.prototype)

But if you explicitly return an object from a constructor function, the this will essentially be discarded, and the returned object will be used instead. Here, the returned object is the function, and the

this.name = "Agnus"

line assigns to an object which is never referenced again.

In contrast, when you don't use new, and the function you call isn't a property of an object (or bound, or an arrow function), this will be either the global object (in sloppy mode), or undefined (in strict mode). In sloppy mode,

function MyClass () {
    this.name = "Agnus"

does

window.name = "Agnus";

And then when you invoke the returned function later with r(), since it's not a property of an object, its this is the global object - whose name is Angus.

To reduce confusion, I recommend

  • Avoiding returning objects explicitly from constructors
  • Always using new when invoking a constructor

You don't have to, but if you do that, you'll confuse yourself (and other readers of the code) less.

Strict mode is a good idea too.

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