Concepts of programming languagesJavascript

What Does the Keyword “new” do in JavaScript?

As an Angular teacher, I often say that JavaScript objects are functions. Most of the time, I get away with this bold claim. It’s not entirely wrong. But it leaves many things in the dark. For one, my short-hand explanation makes it hard to understand why Json objects are objects, too.

By the way, a few hours after publishing this article I remembered that every function is a first-class object in JavaScript. The only property distinguishing it from other objects is that a function can be called. However, this article investigates the other direction. Can every object be defined by a function? Are functions better compared to classes? Or are they something else?

The simple answer

Most of the time, we consider something like this a class in JavaScript:

function Person() {
  this.firstName = "John";
  this.lastName = "Doe";
  this.greet = function() {
    console.log(`Hi ${this.firstName} ${this.lastName}.`);
  };
}
var Person = function() {
  this.firstName = "John";
  this.lastName = "Doe";
  this.greet = function() {
    console.log(`Hi ${this.firstName} ${this.lastName}.`);
  };
}

As long as you create the objects using the new syntax, that’s true enough:

var john = new Person();

console.log(john.constructor.name);  // returns "Person"
console.log(john instanceof Object); // returns "true"

In JavaScript, an object is what you get when you use the new operator on a function. So developers coming from an object-oriented background tend to call the function a class.

Constructor functions

In JavaScript county, people prefer to call it a “constructor function”. It’s a function that’s executed when a new object is created. What’s really happening is this:

  • A new object is created: var john = {};
  • The pointer this is set to this new (currently empty) object.
  • Now, the constructor function is executed. The assignments (such as this.firstName="John") create the attributes of the JavaScript object. Likewise, the assignments of the functions (such as this.greet = function() { ... }) create the methods of the object.
  • For the sake of completeness, let’s mention that the last step is to reset the this to its original value.

Creating objects without new

The description show that you don’t need a function to create a new object. In theory, we could create a new Person like so:

var john = {};
john.firstName = "John";
john.lastName = "Doe";
john.greet = function() {
  console.log(`Hi ${this.firstName} ${this.lastName}.`);
}

Putting the attributes and methods into a Json objects yields a more common syntax:

var john = {
  firstName = "John",
  lastName = "Doe",
  greet = function() {
    console.log(`Hi ${this.firstName} ${this.lastName}.`);
  }
};

I’m told that this is a common pattern in server-side programming with Node.js and the Express framework. Most of the time you don’t need the full power of object-oriented programming. You need classes if you want to create multiple instances of the class. As long as you only need a single object, you need neither classes nor constructor functions.

new considered harmful?

Roughly a decade ago, there was a brief discussion that new should be considered harmful. The idea was that many people discover objects in JavaScript and start using it as an object-oriented programming language without ever learning about prototypes properly. Personally, I wouldn’t go that far, but if you’re interested in the topic, there’s a nice article exploring how to avoid using this and new. However, keep in mind that the article has been written before fat arrow functions become widely used in JavaScript.

Wrapping it up

Strictly speaking, there’s no such thing as a class in JavaScript. Even the class keyword introduced with ES6 is merely syntactical sugar. The closest thing to a class is a function. But in reality, the function serves as the constructor of the class.

By the way, this article deliberately omitted inheritance and scope. Have a look at the “dig deeper” section to learn about the advanced topics, too.


Dig deeper

https://zeekat.nl/articles/constructors-considered-mildly-confusing.html
JavaScript, We Hardly new Ya
JavaScript without “new” and “this”keywords
Object-oriented JavaScript for beginners