Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda