0

我有这个代码片段:

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

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

{
  functionName(args) {
    // statements
  }
}

有人可以解释一下这种语法吗?

4

1 回答 1

3

它是 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;
  }
}
于 2020-08-08T19:09:45.740 回答