2

Compare these two constructors:

A

var Person = function(name, age) {
  this.name = name;
  this.age = age;
}

B

var Person = function(name, age) {
  var o = new Object();
  o.name = name;
  o.age = age;
  return o;
}

Is there a downside to using B over A (other than brevity)?

Edit: The reason I ask is because I can learn by comparing and contrasting the two, not because I want to use B.

5
  • 2
    You waste the object that's already be constructed for you by the runtime system, for one thing. Commented Aug 22, 2014 at 22:19
  • yeah, B is not a constructor since it doesn't include prototype memebers in the output instance. Commented Aug 22, 2014 at 22:19
  • 1
    with B you might as well do var Person = {name:name,age:age}; as that is basically all you are ending up doing Commented Aug 22, 2014 at 22:20
  • B is safer when you forget to use "new " to call a constructor (since it;s not a constructor). Commented Aug 22, 2014 at 22:22
  • 1
    Out of curiosity, what is the upside to that? Commented Aug 22, 2014 at 22:27

1 Answer 1

4

One fairly important difference is that unless you take steps to deal with the issue, the returned object in B would not have the "Person" prototype.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.