Neues Node.js-Buch

Map array values to function parameters

Problem

You want to map values of an array to function parameters in ES5.

Ingredients

  • 1 function
  • 1 array
  • the apply() method

Directions

  1. Given: a function that takes different parameters and an array containing concrete arguments.

    function add(x, y, z) {
      return x + y + z;
    }
    var parameters = [2, 3, 4];
Weiterlesen

Define static properties using the class syntax

Problem

You want to define a static property inside a “class”.

Ingredients

  • 1 “class”
  • 1 property

Directions

  1. Create a “class”.

    class SomeClass {
      constructor(property) {
        this.property = property;
      }
    }
Weiterlesen

Define static methods using the class syntax

Problem

You want to define a static method inside a “class”.

Ingredients

  • 1 “class”
  • 1 method
  • the static keyword

Directions

  1. Create a “class”.

    class SomeClass {
      constructor(property) {
        this.property = property;
      }
    }
Weiterlesen

Apply ES2015 class inheritance

Problem

You want to apply inheritance using the class syntax introduced in ES2015.

Ingredients

  • 2 or more “classes”
  • the extends keyword
  • the super keyword

Directions

  1. Define a “class”. Optionally define some properties, getter and setters.

    'use strict';
    class Animal {
      constructor(color) {
       this._color = color;
      }
      get color() {
        return this._color;
      }
      set color(color) {
        this._color = color;
      }
    }
Weiterlesen

Create getters and setters in class syntax

Problem

You want to create getters and setters for a class in ES2015.

Ingredients

  • 1 class
  • the get and set keywords

Directions

  1. Create a class with some properties.

    class Person {
      constructor(firstName, lastName) {
        this._firstName = firstName;
        this._lastName = lastName;
      }
    }
Weiterlesen