JS中奇怪的函数定义语法

Weird function definition syntax in JS

本文关键字:函数 定义 语法 JS      更新时间:2023-09-26

我在Meteor.js教程中发现了这段代码。这是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,
    });
  },
});

我对这种定义函数的方式很好奇。正如我们所看到的,Meteor.methods被赋予一个对象作为参数,该对象包含函数作为其道具的值。但这到底是什么:

 'tasks.insert'(text) {

我希望"tasks.insert"是一个表示道具名称的字符串,并且该道具名称应该映射到执行插入的函数。但是为什么它不像

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

'tasks.insert': function(text) {

这是一个什么样的模式?这怎么可能是一个有效的JS?

这是一个ES6语法糖。

示例:

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

就像你做了log: function { console.log('hi') } 一样