Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does function declaration by square brackets work in Node.js / Javascript?

First time seeing something like this in Node.js for declaring functions. In short, the code is similar to this

'use strict';
const Actions = {
  ONE: 'one',
  TWO: 'two',
  THREE: 'three'
};
class FunMap {

  run(action) {
    const map = this;
    map[action]();
  }

  [Actions.ONE] () {
    console.log("Performing action one");
  }

  [Actions.TWO] () {
    console.log("Performing action two");
  }

  [Actions.THREE] () {
    console.log("Performing action three");
  }

}

var funMap = new FunMap();
funMap.run('one');
funMap.run('two');
funMap.run('three');

The above program will print

Performing action one
Performing action two
Performing action three

Is there a technical name for this type of function declaration in Node.js / Javascript?

How does this line put all these (functions declared by using the square brackets with a string constant) into property functions of the FunMap object?

const map = this;

Does the square brackets notation [] in a javascript class references the class itself?

like image 562
s-hunter Avatar asked Nov 01 '17 16:11

s-hunter


1 Answers

The syntax with square brackets in the class is called computed property name. The expression inside the square brackets is evaluated, and the result's string value is used as the key.

The code inside the square brackets can't access the class itself, because it's evaluated before the class declaration.

Your example creates a class that looks like this:

class FunMap {

  run(action) {
    const map = this;
    map[action]();
  }

  one () {
    console.log("Performing action one");
  }

  two () {
    console.log("Performing action two");
  }

  three () {
    console.log("Performing action three");
  }

}

The run function uses square brackets in a different way - to look up a property by name. The line const map = this doesn't do anything special - the function would do the same thing like this:

run(action) {
  return this[action]();
}

this[action] means "get the property called action of this". That value is then called as a function with no arguments.

Computed property names were added in ES2015. The subscript syntax for getting an object by its name has been part of JavaScript since the beginning.

like image 168
joews Avatar answered Oct 26 '22 23:10

joews