'New' Keyword in JavaScript

The new operator is often misunderstood and improperly used by programmers just learning JavaScript.

This operator "creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function".

Let's focus on one part a a time. In the sentence above, "constructor" is simply a function.

The following code is a "constructor". There is nothing inherent in JavaScript that makes one function a constructor and another function not a constructor. Any named function is a "constructor".

var Animal = function Animal() {
// Animal constructor code.
};

var animal = new Animal();

What happens when "Animal()" is called with the "new" keyword?

  1. It creates a new Object
  2. It sets the constructor property of the object to Animal.
  3. It sets up the object to delegate to Animal.prototype.
  4. It calls Animal() (The "constructor" function, with the context set as the newly created object. Any reference to "this" inside "constructor" will reference the new object.)

In step 2, there is only a little bit of "magic" going on. Steps 1 and 2 could almost be re-written simply as:

var animal = {};
animal.constructor = Animal;

But, by using the "new" keyword, the .constructor property won't show up when you enumerate over the properties of animal.

Another interesting thing happens in the 3rd step.

animal is set up to "delegate" property lookups to its constructor's prototype property.

For example:

Animal.prototype.bark = "woof"
console.log(animal.bark) // Logs "woof"

But if we like, we can override it without affecting any other Animal.

This the beauty of inheritance, classes, and subclasses.
We can do the following:

var Animal = function(movement) {
  this.move = "move";
};

var genericAnimal = new Animal();

var snake = new Animal();
snake.move = "slither";

var dog = new Animal();
dog.move = "chase car";

console.log(genericAnimal.move); // logs "Move"
console.log(snake.move); // logs "slither"
console.log(dog.move); // logs "chase car"