0

I've discovered this piece of code in the Meteor.js tutorial. It's ES2015:

Meteor.methods({
  'tasks.insert'(text) {
    check(text, String);

    // Make sure the user is logged in before inserting a task
    if (! this.userId) {
      throw new Meteor.Error('not-authorized');
    }

    Tasks.insert({
      text,
      createdAt: new Date(),
      owner: this.userId,
      username: Meteor.users.findOne(this.userId).username,
    });
  },
});

And I'm curious about that way of defining functions. As we can see, Meteor.methods is given an object as a parameter, and that object contains functions as its props' values. But what a heck is that:

 'tasks.insert'(text) {

?? I expect 'tasks.insert' to be a string representing the prop name and that prop name should be mapped to a function that performs inserting. but why isn't it like

'tasks.insert': (text) => {

or

'tasks.insert': function(text) {

What a pattern is that and how does this can even be a valid JS?

Knu
  • 14,806
  • 5
  • 56
  • 89
tristantzara
  • 5,597
  • 6
  • 26
  • 40

1 Answers1

1

This is a ES6 syntatic sugar.

Example:

var a = {
  foo: 'bar',
  log() {
    console.log('hi');
  }
}

a.foo // 'bar'
a.log() // 'hi'

Just the same as if you've done log: function { console.log('hi') }

Felipe Skinner
  • 16,246
  • 2
  • 25
  • 30
  • Thank you and sorry for such a stupid question. I just didn't know how to call it to search for it and decided that placing a code sample would be more convenient – tristantzara May 08 '16 at 16:31
  • [If a function is the value of a property, it gets its name from that property.](http://www.2ality.com/2015/09/function-names-es6.html#methods-in-object-literals) – Knu May 08 '16 at 16:40