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

112
Visualizações
Equivalence of object constructors

Often, when I create an object in Javascscript, I will do something like this:

function getObj(property) {
    return {
        property,
        displayProp: function() {
            console.log(this.property);
        }
    }
}

let obj = getObj("Hello World!);

I know that the usual way to create a constructor would be as such:

function getObj(property) {
    this.property = property;
    this.displayProp = function() {
        console.log(this.property);
    }
}

let obj = new getObj("Hello World!);

Now, my question is, are these two methods equivalent. As far as I can tell, they are the same, and you can also use the 'new' keyword when creating an object using the first case. For me, the first case makes more sense, but it doesn't matter too much to me. Thanks.

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

0

The first example is a function that returns a litteral object (which constructor will remain simply "Object").

The second one creates a new constructor.

function getObj(property) {
    return {
        property,
        displayProp: function() {
            console.log(this.property);
        }
    }
}

// this will be useless because the prototype of getObj is not related to the returned object
getObj.prototype.test_prop = "Test prop"; 

let obj = getObj("Hello World!");
console.log(obj.constructor.name) // Object
console.log(obj.test_prop) // undefined

function Obj(property) {
    this.property = property;
    this.displayProp = function() {
        console.log(this.property);
    }
}

Obj.prototype.test_prop = "Test prop";

obj = new Obj("Hello World!");
console.log(obj.constructor.name) // Obj
console.log(obj.test_prop) // Test prop

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