Javascript Object Class Literal vs. Constructor

Something I dug up while learning Javascript a long, long while ago. Here’s is an interesting article on the differences between a literal class declaration and a constructor. Essentially, the main difference is that with a literal class declaration, the object itself as well as its properties and methods are available right away:

var obj = {
  my_property: 'value',
  my_method: function () {
    console.log('Hello, World!');
  }
};

console.log(obj.my_property); // Logs 'value'
obj.my_method();              // Logs 'Hello, World!'

With a Javascript constructor, the properties and methods will only be available after it’s been instantiated:

var obj = function () {
  this.my_property = 'value';
  this.my_method = function () {
    console.log('Hello, World!');
  };
};

var instance = new obj();
console.log(instance.my_property); // Logs 'value'
instance.my_method();              // Logs 'Hello, World!'

Personally, I prefer the constructor method as you can instantiate however many of the objects you want without the Javascript reference “issue”:

var obj = {
  my_property: 'value',
  my_method: function () {
    console.log('Hello, World!');
  }
};

var obj2 = obj;
obj2.my_property = 'value2';
console.log(obj2.my_property); // Logs 'value2'
console.log(obj.my_property);  // Also logs 'value2'!

If you prefer using the literal class declaration method, as many are, check out this post on how to copy arrays and objects in Javascript.

See davidpirek.com