【问题标题】:Javascript object syntax that I can't recognize我无法识别的 Javascript 对象语法
【发布时间】:2020-11-28 19:43:23
【问题描述】:

我有这段代码:

proxy('http://my-custom-api-endpoint.com', {
  proxyReqOptDecorator(options) {
    options.headers['x-forwarded-host'] = 'localhost:3000'
    return options
  }
})

这是对名为 proxy 的函数的调用,第一个参数是一个字符串,但第二个参数的语法我无法识别:

{
  functionName(args) {
    // statements
  }
}

有人能解释一下这个语法吗?

【问题讨论】:

标签: javascript jsobject


【解决方案1】:

它是 Object Initializer 中用于创建值为函数的属性的简写方法。

// Shorthand method names (ES2015)
let o = {
  property(parameters) {}
}
//Before
let o = {
  property: function(parameters) {}
}

在类中也使用这种语法来声明类方法。

class Animal { 
  speak() {
    return this;
  }
  static eat() {
    return this;
  }
}class Animal { 
  speak() {
    return this;
  }
  eat() {
    return this;
  }
}

【讨论】:

  • 由于您的类示例包含静态方法并使用它,您可能需要澄清一些差异或仅在类示例中使用实例方法
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多