0

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

Bartłomiej Mucha
  • 2,762
  • 1
  • 30
  • 36
  • 1
    Duplicate? http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – Dawson Toth Dec 02 '12 at 19:10
  • 1
    Might want to disambiguate what you're looking for. After reading it a couple times and thinking hard, I'm guessing you're more after "are there performance improvements not using a constructor?". Also, bear in mind no proto-typical-inheritance with ManA. – Dawson Toth Dec 02 '12 at 19:12
  • @DawsonToth there is no prototypal inheritance in either, they are both equal except the second one returns real `ManB` objects while the first one returns plain objects and can be called without `new` – Esailija Dec 02 '12 at 19:21
  • 1
    In this case, the only differences is that `manA instanceof ManA` returns `false` whereas `manB instanceof ManB` returns `true`. – Felix Kling Dec 02 '12 at 19:35
  • I'm interested in any kind of diferences that I should be aware of when using any of these structures eg performance or the one that FelixKling mentioned. – Bartłomiej Mucha Dec 03 '12 at 09:15

1 Answers1

3

The difference is that the manA [[Ptototype]] chain is:

manA -> Object.prototype -> null

and the manB [[Prototype]] chain 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 [see note]. 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 one available is Object.prototype, so every object will inherit them. That is considered very bad style, you should leave built–in objects alone.

RobG
  • 142,382
  • 31
  • 172
  • 209