JavaScript introduced the class keyword in 2015 with the release of ES6. React made classes an indispensable language feature when they introduced support for using extends React.Component instead of React.createClass() in 2015, and removed support for React.createClass() entirely in 2017 in favor of classes. Today, classes are a fundamental part of JavaScript, and many new JavaScript devs don’t remember a time before classes. In this article, I’ll provide an overview of how classes work in JavaScript: how to declare classes, what features JavaScript provides with classes, and how inheritance works.

Working With Classes

Here’s how you define a basic class MyClass, and create an instance of MyClass.

class MyClass {
  constructor() {
    this.answer = 42;
  }
}

const obj = new MyClass();
obj.answer; // 42

You must instantiate a class with new. Calling MyClass() without new throws an error:

// TypeError: Class constructor MyClass cannot be invoked without 'new'
MyClass();

A class is technically a function, although the ECMAScript spec explicitly disallows calling a class without new. In fact, the typeof operator identifies MyClass as a function.

typeof MyClass; // 'function'
MyClass instanceof Function; //  true

To check whether an object is an instance of a class, you should use the instanceof operator. You can also check whether the constructor property is equal to MyClass.

obj instanceof MyClass; // true
// Works, but `instanceof` is better...
obj.constructor === MyClass;

// Because `instanceof` is immune to overwriting the `constructor` property
const obj = {};
obj.constructor = MyClass;
obj instanceof MyClass; // false
obj.constructor === MyClass; // true

Like functions, classes in JavaScript are variables like any other. You can assign a class to a variable, overwrite that class, and pass a class as a parameter to a function. Like functions, you can also declare classes with or without explicit names.

let Foo = class {
  constructor() {
    this.answer = 42;
  }
}

Foo = class {
  constructor() {
    this.answer = 43;
  }
}

console.log(Foo); // '[Function: Foo]'
console.log(new Foo()); // 'Foo { answer: 43 }'

Unlike functions, classes are never hoisted. In the below example the function Foo() prints successfully, because JavaScript looks ahead and ‘hoists’ Foo() to the top of the function. But trying to print the class Bar throws a reference error, because JavaScript does not hoist class definitions.

#es6 #javascript #web-development #programming #developer

An Overview of ES6 Classes
1.70 GEEK