0

If you want to create an object that is unique and is the only instance what's best to use:

var obj = new function() {
  this.x = 200;
  this.y = 100;
};

or

var obj = {
  x: 200,
  y: 100
};

AFAIK the benefits of new is that you can do things such as:

var obj = new function() {
  this.x = 300;
  this.y = x - 50
};

which you can't with:

var obj = {
  x: 300,
  y: x - 50 // undefined
}

???

1 Answers1

2

What about this way?

var obj = {
  init: function() {
     this.x = 300;
     this.y = this.x - 50; 
     return this;
  }
}.init();
Cheery
  • 16,063
  • 42
  • 57
  • Cool, I never thought of something like that, so you could say it's better then because it supports earlier versions of JS that doesn't support the `new` operator, however is it faster? –  Oct 29 '14 at 19:20
  • @Murplyx faster than what? Do you use it thousands of times? I do not think that the difference will be very significant. – Cheery Oct 29 '14 at 19:21
  • @Murplyx: There is no version of js that doesn't support `new`. But `new` does an entirely different thing than you think (the `init` method on the object like in this answer is similar, but at least explicit) – Bergi Oct 29 '14 at 19:24
  • This doesn't really address the question though, does it? – Felix Kling Oct 29 '14 at 19:56