JavaScript is an extremely flexible object-oriented language that has evolved over time. Functionality from the past lives side by side with new functionality that is being added on a daily basis.
Part of that flexibility means you get options. Below I discuss two ways that you can define and instantiate an object in JavaScript!
1. Using Constructor Functions
The most common method for constructing object is through a combination of a function and the keyword new. Below is a simple example:
var Cat = function(name, color){ this.name = name; this.color = color; // methods can be added to the object here // however it is not recommended -- see below! this.meow = function() { console.log("meow!"); }; };
Once the object has been defined, you can call a constructor function to instantiate each Cat.
var cat1 = new Cat('Garfield', 'orange'); cat1.meow(); // logs "meow!" to the console
As mentioned above, the function meow can be defined within our definition of Cat. However, this is not the recommended approach. Instead, it is almost always preferable to add the object's methods to the object's prototype instead.
Each cat-instance doesn't need its own methods saved in memory. Instead, methods can be stored to the Cat object's prototype -- in a single location which is accessible to all instances of cat. Wherever possible use this inexpensive approach instead:
Cat.prototype.meow = function() { console.log("meow!"); };
Using object literals, you can skip the class definition and constructor function entirely and skip directly to creating an instance of your desired object. The below code instantiates code identical to the above quickly and effortlessly:
var cat1 = { name: "Garfield", color: "Orange", meow: function(){ console.log("meow!"); } };
This may be a desirable approach where you only need a single instance of the object -- singletons!
Thanks for reading! Be sure to practice safe JavaScript!