Defining Computed Members

Sometimes we like to give dynamic names to members of a class—that is, to fields, properties, and methods. The approach to achieve this is also useful as a workaround to provide arbitrary names for members, bypassing the language’s restriction on making the members with only alphanumeric characters.

Recall using special method names like Symbol.search and Symbol.iterator in Chapter 4, Iterators and Symbols. Writing a method named Symbol.iterator() {} will result in an unexpected token error. We had to place it within [], like so: [Symbol.iterator]() {}.

To create a computed property, we place a variable containing the name of the property as the value in []. Alternatively, we can place a string or a template literal within [] as well. Let’s explore this with an example.

 const​ NYD = ​`New Year's Day`​;
 
 class​ Holidays {
 constructor​() {
 this​[NYD] = ​'January 1'​;
 this​[​"Valentine's Day"​] = ​'February 14'​;
  }
 
  [​'list holidays'​]() {
 return​ Object.keys(​this​);
  }
 }

NYD is a variable that contains the value evaluated from a template literal. In essence, it contains the string "New Year’s Day" as its value. Within the constructor of the Holidays class, we use the variable NYD to create a computed field with the contained string as field name.

Instead of using a variable, we may also embed a string or template literal directly within the [], like we do for the field named "Valentine’s Day" or the method named ’list holidays’.

In addition to defining computed fields and methods within the class, we can add them to an instance, like so:

 const​ usHolidays = ​new​ Holidays();
 usHolidays[​'4th of July'​] = ​'July 4'​;

The object usHolidays is an instance of the Holidays class but has an additional computed field named 4th of July.

To access a computed field, place its computed name within []. If that expression appears on the left side of an assignment, the value on the right side of the assignment is assigned to that field. For example, the string ’July 4’ is assigned to the computed field ’4th of July’ in the previous code. Let’s access the value of a computed field and also invoke a computed method.

 console.log(usHolidays[​`Valentine's Day`​]);
 const​ methodName = ​'list holidays'​;
 console.log(usHolidays[methodName]());

Even though we defined the field Valentine’s Day using a string, we are referring to it using a template literal—that’s no problem as the template literal evaluates to the same string. To invoke the method named list holidays, we either place that string, or a variable containing that string, inside [], like methodName, which contains that string as value. The () after the [] tells JavaScript to invoke as a method instead of accessing the computed name as a field.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset