Making Object Instances in JavaScript

Part 2: ES6 Classes

Kamie Robinson
2 min readJul 28, 2017

In JavaScript, there are several ways to use object initializers and make an object instance, from writing an object literal, to functional instantiation patterns, to ES6 classes and subclassing. Knowing how to implement every possible way is commendable. Having a solid reason why you choose a particular way gets respect.

If you are not sure about the different instantiation options or which one to choose, this two-post series provides an overview of things to consider as you decide.

The first post covers common initializers and functional instantiation patterns. This second post goes over ES6 classes.

ES6 classes

ES6 classes instantiate objects just like pseudoclassical. In pseudoclassical, the interpreter takes care creating the prototype, creating an object instance that delegates to the prototype, and returning the new object instance. The same is true for classes. The differences are definition syntax and that class definitions are not hoisted. This means that a class has to be defined in your code BEFORE the instance can be created.

Classes can be defined in two ways:

1) as an expression

//CLASS EXPRESSION//set a variable equal to a class
var Song = class {
...
}

2) or as a declaration

//CLASS DECLARATION//use the keyword class followed by the name of the class
class Song {
...
}

If for some reason you would like to declare the class, then redeclare it again somewhere in your application, be sure to use a class expression.

A few things to note about ES6 classes:

  • Every class can have one constructor function. The constructor function is where unique properties are set on each instance.
class Dot {         
constructor(color, size) {
this.color = color;
this.size = size;
}
}
  • Unique property values will be passed as arguments when the object is instantiated.
var polka = new Dot('yellow', '10px');
  • Other functions contained in the class are methods added to the prototype.
class Dot {         
constructor(color, size) {
this.color = color;
this.size = size;
}
draw() {
//add the dot to the DOM
//code to do this will depend on your environment
}
}

--

--

Kamie Robinson

Software Engineer rooted as a Creative. Writing how-tos and about 'ahas' and 'gotchas' of making.