2

It seems that in Javascript everything can be done in several ways. My confusion is about Object creation.

First way:

var myObject = new Object();
myObject.name = 'Salko_Crni';;
myObject.someFunction = function() {
   console.log(this.name);
}

Second Way:

var myObject = {
   name: 'Salko_Crni',    
   someFunction : function() {
      console.log(this.name);
   }
};

Some literature mentions to use more robust literal method.

In my view (beginner), it looks more robust to use new Object();

But, who am I to tell?

Salko Crni
  • 45
  • 7
  • 3
    Ultimately it's a matter of opinion, but I don't know any good reason to prefer explicit calls to `new Object()`, as using an object literal will do the exact same thing anyway. – Pointy May 31 '17 at 14:31
  • One notable difference is the first approach mutates the object, while the second approach creates only 1. Recent development trends have started to really look down on mutation as a performance bottleneck. – ilrein May 31 '17 at 14:31
  • The second way is more DRY, as you have to mention the variable name `myObject` only once. – Bergi May 31 '17 at 14:33
  • 1
    Define "robust". – Dave Newton May 31 '17 at 14:34
  • If that object is a singleton, I'd argue that both ways are fine. If it isn't, then IMO both are bad and you should instead go for constructors and prototypes. – Siguza May 31 '17 at 14:36
  • @DaveNewton The robustness that also [makes it faster](https://stackoverflow.com/q/21545687/1048572) – Bergi May 31 '17 at 14:38
  • @Bergi That'd make `{}` more "robust" I guess. – Dave Newton May 31 '17 at 14:40
  • @DaveNewton Oh, I didn't notice that the OP himself also called `new` "robust". I meant to agree with the literature :-) – Bergi May 31 '17 at 14:45

1 Answers1

1

There is no right and wrong when it comes to design patterns. The best choice is the one that works best for your situation. Also, there is actually a 3rd way to instantiate an object using Array syntax.

var YourObject = {};
YourObject['property_1'] = value;
YourObject['property_2'] = value;
YourObject['method'] = function(){ /* function code here */ }
Korgrue
  • 3,430
  • 1
  • 13
  • 20
  • What is "array syntax"? Your example code is no different from what the OP does. – Bergi May 31 '17 at 14:35
  • you mean **bracket notation**, a method of accessing objects. – Nina Scholz May 31 '17 at 14:35
  • 1
    Bracket, Array, depends on what book you read. As far as what it does different. Absolutely nothing. It is just a 3rd design pattern for instantiating objects. – Korgrue May 31 '17 at 14:36
  • How would it be a third pattern if it's not different from the first? That way, we could also devise a "fourth" way: `var myObject = {["name"]: …, ["someFunction"]: …};` (and both are bollocks when you don't need dynamic property names) – Bergi May 31 '17 at 14:40
  • His first example uses the "new" keyword. It is not an object literal. – Korgrue May 31 '17 at 14:48