Anya M.
Anya M.

Reputation: 61

What is the difference between a constructor function and function returning an object?

How are they different and why would you use one over the other?

For example:

function setupOptionsObj(num) {
  return {
    data: num,
    func: function() {
      return num * 10
    }
  }
}

function setupOptionsConstructor(num) {
  this.data = num;
  this.func = function() {
    return num * 10
  }
}

var one = setupOptionsObj(123)
var two = new setupOptionsConstructor(123)

console.log(one.func());
console.log(two.func());

Thank you :)

Upvotes: 0

Views: 52

Answers (1)

Barmar
Barmar

Reputation: 781741

setupOptionsObj() returns a plain object.

new setupOptionsConstructor() returns an object whose prototype is setupOptionsConstructor.prototype.

Prototypes allow you to add methods and properties that apply to all objects created by that constructor. This is the basis of JavaScript's prototype-based object-oriented programming.

For example, below we only have one foo function, not one in every object.

function setupOptionsConstructor(num) {
  this.data = num;
}

setupOptionsConstructor.prototype.func = function() {
  return this.data * 10
};

var two = new setupOptionsConstructor(123);
var three = new setupOptionsConstructor(456);

console.log(two.func());
console.log(three.func());

Upvotes: 2

Related Questions