Neues Node.js-Buch

Apply pseudoclassical inheritance

Problem

You want to use pseudoclassical inheritance, i.e., create a “class” as “subclass” of another “class”.

Ingredients

  • 2 or more functions
  • the prototype property
  • the call() method

Directions

  1. Define a function intended to be a constructor function (this will be the “superclass”).

    function Animal(color) {
      this._color = color;
    }
Weiterlesen

Convert arguments object to array

Problem

You want to convert the array-like object arguments to a real array.

Ingredients

  • the Array prototype
  • the slice() method
  • the call() method

Directions

  1. Given: a function that takes different parameters and accesses them via the arguments object.

    function printAllArguments() {
      let values = arguments;
      for(let i=0; i<values.length; i++) {
        console.log(values[i]);
      }
    }
    printAllArguments(2, 3, 4);
Weiterlesen

Emulate block level scope

Problem

You want to emulate block level scope in ES5 to prevent naming conflicts.

Ingredients

  • Immediately-Invoked Function Expression (IIFE)

Directions

  1. Given: some code that you want to put in a block.

    var aVariable = 2345;
    // Block should start here
    var aVariable = 4711;
    console.log(aVariable);      // should print 4711
    // Block should end here
    console.log(aVariable);      // should print 2345, but prints 411
Weiterlesen