Hegwin.Me

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

Learn New Features in ES 2015 Part 1

学习ES2015 Part 1

Variable declaration

Declaring variables with let

  • Finally, no more var hoisting problem, you can declare block-level variables now (cheers)

  • Solve the problem of variable leakage in for loops.

  • Variables declared by let in the same block can be reassigned, but declaring variables with the same name again will throw an exception TypeError

Declare variables using const

  • Declare a read-only variable that must be assigned a value when it lives

  • Assigning a value to a const variable will usually result in an error, but some browsers will handle it silently

  • Magic numbers can be avoided

About Functions

Default values for parameters

function loadProfiles(userNames= []) {
  let namesLength = userNames.length;
  console.log(namesLength);
}

Named parameters

Before, we can write it like this

function setPageThread(name, options={}) {
}

Now you can give the parameters in options names

function setPageThread(name, { popular, expires, ativeClass }={}) {
}
  • Enhanced parameter readability

  • Avoid boilerplate codes

  • It will be undefined if no parameters are passed

Rest Parameters

I don't know how to explain this one, but it's a behavior that eats the rest parameters together at the end of the passed parameters, and I think JS is becoming more and more like Ruby at this point.

For example, we define a method like this: ```js function displayTags(targetElement, ...tags) { let target = _findElement(targerElement); for (let i in tags) { let tag = tags[i]; _addToTopic(target, tag); } }

Note: ... is a new spread operation added in ES2015, which will be used many times in the future.

So, we can call this method like this.

displayTags(targetDiv, 'ruby', 'meta', 'structure').

Using the arrow method

For =>, there is a rather important sentence

Arrow functions bind to the scope of where they are defined, not where they are used. (Also known as lexical binding)

The short answer is, oh yeah, I finally don't have to struggle with what this in JS refers to.

function TagComponent(target, urlPath) {
  this.targetElement = target;
  this.urlPath = urlPath;
}

TagComponent.prototype.render = function() {
  getRequest(this.urlPath, (data) => {
    let tags = data.tags;
    displayTags(this.targetElement, . . tags);
  })
}

This has (data) => { }, the function is bound to the lexcical scope, if you use the traditional function(data) {}, when calling this.targetElement, you will use this anonymous method's own scope.

< Back