-1

What is the recommended constructor for JavaScript objects?

Constructor 1

var myObject = new Object();
myObject.name = "Jim"
myObject.age = 24;

Constructor 2

var myObject = {}
myObject.name = "Jim"
myObject.age = 24

Constructor 3

var myObject = {
name: 'Jim',
age: 24
}
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
Jim Moody
  • 758
  • 2
  • 6
  • 18
  • 2
    I believe this question is opinion-based, nothing else. – silentw Dec 05 '14 at 17:15
  • However, to initialize a constructor, I use method 3. If I want to change something on the road, obviously I use the second method. – silentw Dec 05 '14 at 17:17
  • 1
    You missed one - if you're building reusable objects: `function myObject(name, age) { this.name = name; this.age = age; } var obj = new myObject("Jim", 24);` This is what I think of when you're talking about a JavaScript Constructor – James Thorpe Dec 05 '14 at 17:18
  • What do *you* think is the best way and why? – Felix Kling Dec 05 '14 at 17:25
  • Other than the call for the constructor for the `Object`, none of these even use constructors. A constructor is a method call for an object when it's created, then called when you use `new myObject(...)` – Spencer Wieczorek Dec 05 '14 at 17:33
  • The link provided at the top of this is exactly what I wanted, sorry for the duplicate question – Jim Moody Dec 30 '14 at 13:43

1 Answers1

1

You should use the Constructor 2 or 3 (whatever you want) but never use Constructor 1 (is a bad practice):

The advantages of object literals over using the respective constructor are:

  • Shorter and more readable.
  • Safer: literals will still work when the Object constructors have been overridden.
  • Possibly faster, though it's unlikely to be a major consideration.

[Update]

Try always use constructor 3 because is more performant but take in mind that you can use the Constructor 2 approach if you later need to append properties to your object.

ianaya89
  • 4,153
  • 3
  • 26
  • 34
  • 1
    The problem with number 2 is that you are performing a bunch of assignments. Not so bad when it's just two properties, but a potentially huge hit on bigger objects. Method 3 is a single operation. I found this out the hard way when I was 12 and thought it was a good idea to build an entire database in JavaScript by doing `data[123].name.english = "Abc"; data[123].name.french = "Merde";` over and over and over XD – Niet the Dark Absol Dec 05 '14 at 17:17
  • @NiettheDarkAbsol You are right, what I try to explain is that sometime could be useful if you need to append new properties to your object. Thanks for the contribution. – ianaya89 Dec 05 '14 at 17:18