Search code examples
javascriptsyntaxobject-literal

What is this 'method-like' syntax in JS object literal


Use ES6 class sugar, we can define function this way:

class Foo {
  constructor(props) {}
  ...
  myFn() {}     
} 

and in JS object literal, we can define getters and setters like this:

foo = {
  get data() {}
  set data(val) {}
}

However, what's this syntax:

foo = {
  data() {}
} 

Is this object data properties? Or getters/setters?

note: this syntax is extensively used in Vue.js 2.0 doc, like the new added render function.

new Vue({
  render (h) {
    throw new Error('oops')
  },
  renderError (h, err) {
    return h('pre', { style: { color: 'red' }}, err.stack)
  }
}).$mount('#app')


Solution

  • its just shorthand. refer to MDN docs

    // Shorthand method names (ES2015)
    var o = {
      // doesnt need a colon!
      property([parameters]) {},
      get property() {},
      set property(value) {}
    };