ariya.io About Collections Archives

ECMAScript 6 and Method Definitions

2 min read

Using an object literal populated with some member functions is a common practice in any serious JavaScript applications. This is also useful for all kind of frameworks, in particular to setup object prototypes. The upcoming ECMAScript 6 introduces method definition, a nice shorthand which eliminates the need to use function when using that pattern.

Before we see method definition in action, let us have a quick refresh on property setter and getter. This is part of the current ECMAScript 5.1, see Section 11.1.5 on Object Initialiser. The idea is to use set and get to bind an object property to a function which will be invoked when that property is set and looked up, respectively. The following code fragment demonstrates its usage:

var BigLoco = {
  locoName: 'Gordon',
  get name() { return this.locoName; },
  set name(n) { this.locoName = n }
};
 
console.log(BigLoco.name); // 'Gordon'

Practically, we have a way to define a function without using the function keyword. With ECMAScript 6, this is extended further so that the syntax applies not only to property getter and setter, but also to plain functions. This is called Method Definitions, see Section 13.3 in the latest ES6 draft.

Take a look at an example ECMAScript 6 code here, in particular to the start and stop functions.

var SteamEngine = {
  color: 'blue',
  get name() { return 'Thomas' },
  start() { console.log('Hurry up!'); },
  stop() { console.log('Screech...! That was close.'); }
};
 
console.log('My name is', SteamEngine.name);
SteamEngine.start();
SteamEngine.stop();

If we were about to transpile the code to ES5, the construct will look like:

var SteamEngine = {
  color: 'blue',
  get name() { return 'Thomas' },
  start: function() { console.log('Hurry up!'); },
  stop: function() { console.log('Screech...! That was close.'); }
};

The ECMAScript 6 version shows a nice symmetry thanks to this syntactic sugar. Every property on that literal looks the same and it’s not really difficult to spot the functions due to the necessary parentheses. Sweet!

Related posts:

♡ this article? Explore more, check the archives, or follow me Twitter.

Share this on Twitter Facebook Google+

comments powered by Disqus