JavaScript: constructor function - what can go wrong?

Wojciech Trawiński
JavaScript everyday
3 min readSep 3, 2018

Description

Object creation can be accomplished in JavaScript in several manners, namely:

  • using an object literal,
  • with the aid of constructor function,
  • using Object.create method,
  • with the aid of class keyword,
  • using module pattern (however it’s all about returning an object literal).

I won’t tell you which of the aforementioned ways is the best one, since I even one of my two JavaScript Gods gave me a misleading response when I asked: ‘Bartosz, how should I create objects in JavaScript?’.

Goal

The main aim of today’s post it to point out two major mistakes which can be made when you create objects using the constructor function approach.

Like a boss

Let’s start with a proper example on how to use a constructor function.

You need to create a function which name should be start with a capital letter. Within the function’s body you have an access to a Car instance via this variable. This will hold the reference to a newly created object. Methods shared by all instances of Car can be added to its prototype. In order to create a Car object, you need to call the constructor function with a leading new keyword. Once the function has executed, a reference to the newly created object will be stored in the myFerrari variable.

C++/Java background pays off

The same JS God says that it is worth to be familiar with more than one programming language. If you have some experience with C++ or Java, it will be obvious for you that when you create an object you need to use the new keyword next to a constructor’s call. Let’s see what happens if you forget about it.

If you use the Car constructor function from the first example, you will set brand and model properties on the global object (window if you run this code in a web browser). As a result, you will add undesired properties to the global object and the myFerrari constant will have undefined value.

However, if you use the strict mode within the Car function’s body, you will get a TypeError, since this will be set to undefined instead of the global object. As you can see, the strict mode is a good choice, since you won’t add any properties to the global object by mistake.

Never return

You may be tempted to return something from a constructor function. If you return an object from within the function, you will get into troubles.

If you run the above code, you will see that instead of a Car instance,the myFerrari constant keeps a reference to the object returned from the constructor function.

Remarks

If you use a constructor function to create an object in JavaScript, you should never:

  • forget about the new keyword when calling a constructor function,
  • return from a constructor function.

In addition, using the strict mode can prevent from silent bugs which can be harmful.

Like, love, hate, clap!

--

--