Book Image

ECMAScript Cookbook

By : Ross Harrison
Book Image

ECMAScript Cookbook

By: Ross Harrison

Overview of this book

ECMAScript Cookbook follows a modular approach with independent recipes covering different feature sets and specifications of ECMAScript to help you become an efficient programmer. This book starts off with organizing your JavaScript applications as well as delivering those applications to modem and legacy systems. You will get acquainted with features of ECMAScript 8 such as async, SharedArrayBuffers, and Atomic operations that enhance asynchronous and parallel operations. In addition to this, this book will introduce you to SharedArrayBuffers, which allow web workers to share data directly, and Atomic operations, which help coordinate behavior across the threads. You will also work with OOP and Collections, followed by new functions and methods on the built-in Object and Array types that make common operations more manageable and less error-prone. You will then see how to easily build more sophisticated and expressive program structures with classes and inheritance. In the end, we will cover Sets, Maps, and Symbols, which are the new types introduced in ECMAScript 6 to add new behaviors and allow you to create simple and powerful modules. By the end of the book, you will be able to produce more efficient, expressive, and simpler programs using the new features of ECMAScript. ?
Table of Contents (20 chapters)
Title Page
Copyright and Credits
Dedication
PacktPub.com
Contributors
Preface
Index

Using throw to simulate abstract classes


So far, we've seen how to create and combine classes into a variety of different shapes. Sometimes, however, we want to be able to prevent the creation of a class and only allow instances of extending classes. Other languages provide a facility known as abstract classes. In this recipe, we'll see how to simulate this by throwing errors.

Getting ready

This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.

How to do it...

  1. Open your command line application and navigate to your workspace.
  2. Create a new folder named 08-10-use-throw-to-simulate-abstract-class.
  3. Copy or create an index.html that loads and runs a main function from main.js.
  1. Create a main.js file that defines a new class named Rocket. In the constructor, check the constructor of the instance, if it's Rocket, then throw an error:
// main.js 
class Rocket { 
  constructor (name) { 
    this.name ...