Bartłomiej Mucha
Bartłomiej Mucha

Reputation: 2782

How does a factory function returning an object literal differ from a constructor?

Is there any difference between creating new object like in function ManA or by calling constructor ManB?

function ManA(name, age)
{
    return { name: name, age: age, getAge: function() { return this.age; } };
}
    
function ManB(name, age)
{
    this.name = name;
    this.age = age;
    this.getAge = function() { return this.age; };
}

var manA = ManA("Tom", 28);
var manB = new ManB("Frank", 25);

Thanks

Upvotes: 1

Views: 93

Answers (1)

RobG
RobG

Reputation: 147343

The difference is that the prototype chain for manA is:

manA → Object.prototype → null

and the prototype chain for manB is:

manB → ManB.prototype → Object.prototype → null

so in the second case, you can add methods to manB (and all instances of ManB) by adding them to ManB.prototype. You can't do that with ManA instances (though see note below). So the getAge method can be on the constructor's prototype, saving a few bytes of memory for each instance.

Note

You can add methods to the manA prototype chain, but the only object in the chain available is Object.prototype, so every object will inherit them. That is considered very bad style; you should leave built–in objects alone.

Upvotes: 4

Related Questions