.

Tags:

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!

Ariya Hidayat

Software Provocateur
These days, I promote software craftsmanship around web technologies. If you like this article, read also other similar blog posts and follow me @ariyahidayat.

Latest posts by Ariya Hidayat (see all)

  • ernest

    not sure about this syntax. for me is kind of nice to have “function” easy and quick to spot when skimming code.

    • http://ariya.ofilabs.com/ Ariya Hidayat

      For me, it’s faster to spot the (). A quick look will not reveal whether a property is a function or not as we need to scan further past the colon (:) and finally see the “function” keyword.

  • Cyril Moreau

    Great ! How to use the setter ? (set name(n) ). This way ? BigLoco.name = ‘Flash’;
    So locoName will be ‘Flash’, true ? just tested it in Chrome Stable Channel (25.0), and the behavior is strange …

    var BigLoco = {
    locoName: ‘Gordon’,
    get name() { return this.locoName; },
    set name(n) { this.locoName = n }
    };

    console.log(BigLoco); // BigLoco.loconame is already Flash when you “deploy” the Object console.log(BigLoco.locoName); // works fine, outputs Gordon
    BigLoco.name = ‘Flash’;
    console.log(BigLoco); //ok

    • http://ariya.ofilabs.com/ Ariya Hidayat

      What’s exactly strange about this? Please read some other resources on how ES5 property setter/getter works.

    • http://tbassetto.github.com Thomas

      In recent versions of Chrome, you should see a PREVIEW [1] of the BigLoco object containing “Gordon” next to the first console.log(BigLoco);

      But when your “deploy” it, Chrome lazily evaluate the expression, and at that time the name is Flash.

      [1] https://bugs.webkit.org/show_bug.cgi?id=35801

  • steve

    I recognise the importance of cleaning up code and removing repetition. I
    prefer c# to java, but you should only go so far before the code loses
    readability. It’s like going backwards from well formed xhtml to html 3.2. English to Text speak. George Orwells book 1984 double speak. What’s next: Leaving out curly braces for json? I don’t think removing the word ‘function’ is particularly beneficial. What does it gain in terms of extra time – 1 second to type the word ‘function’, and time lost on readability. Some languages are concise and brilliant – Regex, but some are just messy s$$$.

    • http://ariya.ofilabs.com/ Ariya Hidayat

      Readability can be subjective. I personally find it easier to spot a function via its immediate (). Others may have different opinions. If you care to enlighten me on how the new construct is not readable, that will be better appreciated.

      Also, passionate JavaScripts are always needed. I highly recommend talking to those TC-39 members and others domain experts via the proper channel (i.e. es-discuss list) so that everyone can benefit from your expertise!

  • http://twitter.com/jimfeedback jim

    Are we going forward or backwards? The fact that some C/C#/Java programmers are trying to pass principles and conventions from these languages to JavaScript makes me sick.

    The above code Is messy and you can easily get confused and start wondering if you are inside an object declaration or not when you read bigger code.

    Using named functions like this inside an object without keeping object related conventions is just a mess.

    • http://ariya.ofilabs.com/ Ariya Hidayat

      I understand that messy code is annoying. However, simply stamping something as a mess does not educate me as to why it is the case.
      I’ve been doing JavaScript only for a few years. Care to explain the situation “if you are inside an object declaration or not when you read bigger code” in slightly more details?

      • Denom

        When was the last time that any of the ECMAScript editors had read the JavaScript Object Notation reference (see: http://www.json.org/) ?

        The first description refers to what is an Object in javascript; Key/Value pairs where every subsequent is comma separated from the previous one wrapped in curly brackets.

        As key/value pair is defined as a string (key) on the left hand-side SEPARATED BY A SEMICOLON from a value on the right hand-side.

        Define what exactly is the “ECMAScript 6 Method Definitions” in terms of JavaScript. As fancy is the name, that much ugly is the implementation.

        • http://ariya.ofilabs.com/ Ariya Hidayat

          I personally don’t necessarily agree that future object literal should be limited to JSON (itself is a subset of ES). A function is never allowed anyway in JSON.

      • http://twitter.com/jimfeedback jim

        What I meant is the same that has been said bellow . The method definition that is being suggested is simply unproductive and not clean!

        Try to describe me what exactly is this.

        At the very beginning I was expecting to see some augmentation of the Object and Function instances in the same way Object.defineProperty was heading on but improved in some aspects like the elimination of the need to create private var in closure in order to define setter/getter, Function.defineMethod(obj,start(){//code},descriptor) and Function.defineMethods(…) like implementations so you could easily break your object in properties and methods but still the basic conventions in javascript would remain intact. Removing this conventions and throwing a bit of everything in the object’s body will only lead to confusion.

        • http://ariya.ofilabs.com/ Ariya Hidayat

          If you have a different expectation and/or some ideas, then what stops you from discussing them in the proper channel (e.g. es-discuss)?

          Throwing one bad adjective after another (joining that growing list of “messy”, “unproductive”, “not clean”) will be fine and dandy, though I seriously doubt that it will change anything.

  • http://twitter.com/Rickenhacker Daniel Earwicker

    Seems like a no-brainer to me.

  • Mani Tadayon

    There is something to be said for the simplicity of JavaScript objects as key/value pairs. It seems like JavaScript is becoming more like Ruby, where the number of syntactic rules and overall complexity are always increasing. I’d prefer to see JavaScript go more in the direction of functional languages like Clojure, which favor simplicity and consistency…