DEV Community

Discussion on: ES6 Mini Crash Course: How to Write Modern JavaScript

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

This is a fantastic write-up of the core ES6 benefits! I just wanted to note that if performance is a concern for functions bound to this, then the handleEvent API carries infinitesimal overhead compared to the arrow function syntax and bind(this) calls within the constructor.

const clickCounter = {
  submit: 0,
  reset: 0,
  elements: {},

  // `this` will be `clickCounter`
  handleEvent({currentTarget, type}) {
    if (type === "click") {
      this.incrementClicks(currentTarget);
    }
  },

  // `this` will still be `clickCounter`!
  incrementClicks(currentTarget) {
    const {localName, type} = currentTarget;
    localName === "button" ? this[type]++ 
      : (this.elements[elTag(currentTarget)] || this.elements[elTag(currentTarget)] = 0)++;
  },

  elTag({localName, classList, id}) {return [
      localName,
      id ? `#${id}` : null,
      classList.length ? `.${[...classList].join(".")}` : null
    ].join("");
  }
}

// count ALL the clicks!!
document.addEventListener("click", clickCounter);