Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!