Translate

Thursday 9 January 2020

JavaScript’s New Private Class Fields, and How to Use Them

JavaScript's New Private Class Fields, and How to Use Them

ES6 introduced classes to JavaScript, but they can be too simplistic for complex applications. Class fields (also referred to as class properties) aim to deliver simpler constructors with private and static members. The proposal is currently a TC39 stage 3: candidate and is likely to be added to ES2019 (ES10). Private fields are currently supported in Node.js 12, Chrome 74, and Babel.

A quick recap of ES6 classes is useful before we look at how class fields are implemented.

ES6 Class Basics

JavaScript's object-oriented inheritance model can confuse developers coming from languages such as C++, C#, Java, and PHP. For this reason, ES6 introduced classes. They are primarily syntactical sugar but offer more familiar object-oriented programming concepts.

A class is an object template which defines how objects of that type behave. The following Animal class defines generic animals (classes are normally denoted with an initial capital to distinguish them from objects and other types):

class Animal {

  constructor(name = 'anonymous', legs = 4, noise = 'nothing') {

    this.type = 'animal';
    this.name = name;
    this.legs = legs;
    this.noise = noise;

  }

  speak() {
    console.log(`${this.name} says "${this.noise}"`);
  }

  walk() {
    console.log(`${this.name} walks on ${this.legs} legs`);
  }

}

Class declarations always execute in strict mode. There's no need to add 'use strict'.

The constructor method is run when an object of the Animal type is created. It typically sets initial properties and handles other initializations. speak() and walk() are instance methods which add further functionality.

An object can now be created from this class with the new keyword:

let rex = new Animal('Rex', 4, 'woof');
rex.speak();          // Rex says "woof"
rex.noise = 'growl';
rex.speak();          // Rex says "growl"

Getters and Setters

Setters are special methods used to define values only. Similarly, Getters are special methods used to return a value only. For example:

class Animal {

  constructor(name = 'anonymous', legs = 4, noise = 'nothing') {

    this.type = 'animal';
    this.name = name;
    this.legs = legs;
    this.noise = noise;

  }

  speak() {
    console.log(`${this.name} says "${this.noise}"`);
  }

  walk() {
    console.log(`${this.name} walks on ${this.legs} legs`);
  }

  // setter
  set eats(food) {
    this.food = food;
  }

  // getter
  get dinner() {
    return `${this.name} eats ${this.food || 'nothing'} for dinner.`;
  }

}

let rex = new Animal('Rex', 4, 'woof');
rex.eats = 'anything';
console.log( rex.dinner );  // Rex eats anything for dinner.

Child or Sub-classes

It's often practical to use one class as the base for another. A Human class could inherit all the properties and methods from the Animal class using the extends keyword. Properties and methods can be added, removed, or changed as necessary so human object creation becomes easier and more readable:

class Human extends Animal {

  constructor(name) {

    // call the Animal constructor
    super(name, 2, 'nothing of interest');
    this.type = 'human';

  }

  // override Animal.speak
  speak(to) {

    super.speak();
    if (to) console.log(`to ${to}`);

  }

}

super refers to the parent class, so it’s usually the first call made in the constructor. In this example, the Human speak() method overrides that defined in Animal.

Object instances of Human can now be created:

let don = new Human('Don');
don.speak('anyone');        // Don says "nothing of interest" to anyone

don.eats = 'burgers';
console.log( don.dinner );  // Don eats burgers for dinner.

The post JavaScript’s New Private Class Fields, and How to Use Them appeared first on SitePoint.



No comments:

Post a Comment