Methods and Namespaces

Method Definitions and Namespaces

Method shorthand name() {} stores a function in a property; the syntax also covers getters, setters, generators and async methods. Shorthand methods cannot be called with new, and method definitions are the only functions in a literal that can use super. Before modules, libraries grouped their functions in one global namespace object such as jQuery 561 ; an ES module (Export and Import) now does that job.

Method shorthand, accessors and a generator methodJavaScriptLive
const counter = {
  count: 0,
  increment() { return ++this.count; },          // method shorthand
  get double() { return this.count * 2; },       // getter
  set value(v) { this.count = Number(v); },      // setter
  *[Symbol.iterator]() { for (let i = 1; i <= this.count; i++) yield i; },
};
counter.value = "3";
console.log(counter.increment(), counter.double, [...counter]);