Hegwin.Me

In silence I feel full; With speech I sense emptiness.

Learn New Features in ES 2015 Part 2

学习ES2015 Part 2

String

ES2015 has added the concept of Template String, so we don't need to keep using + when we want to stitch variable values into the middle of a string, which is what I think we can cheer about.

This is how it works: the normal string in JS is still surrounded by single or double quotes, but the Template String is surrounded by backquotes (I feel like it's killing me to put backquotes in Markdown).

In the past: let fullName = firstName + ' ' + lastName.

Now: let fullName = `${firstName} ${lastName}`

where we use ${} to enclose the variable.

Using this approach, we can also construct long strings of multiple lines:

let userName = 'Same';
let admin = { fullName: 'Hegwin Wang' };

let aLongText = `Hi ${userName}
This is a very
loooooooooog text.

Regards.
${admin.full_name}
`;

Class

Class syntax

ES2015 added class syntax, but as far as I know, this is just an addition of something like syntactic sugar, the essence of JS implementation of OO is still the same as the original. For example:

class TagWidget {
  constructor(name,url) {
    this.url = url;
    //...
  }

  render() {
    let link = this._buildLink(this.url);
    // ...
  }

  _buildLink() {
    // ...
  }
}

In this code, we use the class keyword to declare a class, and then surround it with curly braces, with several methods inside, with no commas or semicolons separating the methods.

  1. The code in constructor will be executed whenever we create a new instance with new, similar to Ruby's initialize.

  2. The content accessed by this is an instance property, or an instance method.

  3. Methods that start with an underscore, like _buildLink in the example, are private methods.

For the class declared above, we can call it like this:

let tagWidget = new TagWidget(name, url);
tagWidget.render();

Class inheritance

Suppose we have a class like Widget that we intend to use as the parent of all widget classes:

class Widget {
  constructor() {
    this.bassCSS = 'widget';
  }

  parse(value) {
    // ...
  }
}

The new syntax allows the use of extends to specify the parent class, assuming that TagWidget now inherits from the Widget class:

class TagWidget extends Widget {
  constructor(name, url) {
    super();
    // ...
  }

  parse() {
    let parseName = super.parse(this.name);
    return `Tag: ${parsedName}`;
  }

  render() {
    // ...
  }
}

In this case super can be used to call the methods of the parent class; also the return value of parse in TagWidget uses the methods of Template String as mentioned above.

< Back