ES6:无法在调用构造函数中解构

时间:2017-05-27 02:42:09

标签: javascript ecmascript-6 javascript-objects object-literal es6-class

我试图在类构造函数中使用ES6解构但得到一个未知的令牌错误。这是一个例子:

// imports / server / a-and-b.js

class A {
  constructor(id) {
    // make MongoDB call and store inside this variable
    let {
      firstName: this._FirstName // => Throws here
    } = CollectionName.findOne({userId: id});
  }
}

export class B extends A {
  constructor(id) {
    super(id);
  }
  get FirstName() {
    return this._FirstName;
  }
}

// imports / server / test.js

import { B } from 'imports/server/a-and-b.js'

const b = new B('123')

const FirstName = b.FirstName;

同样的解构将在课外开展:

// another-test.js

// make MongoDB call and store inside this variable
let {
  firstName: FirstName // works fine
} = CollectionName.findOne({userId: id});

2 个答案:

答案 0 :(得分:4)

您的语法不正确。你想要做的是不可能的。假设findOne方法是同步的,您需要这样做:

constructor(id) {
    // make MongoDB call and store inside this variable
    let { firstName } = CollectionName.findOne({userId: id});
    this._FirstName = firstName;
  }

答案 1 :(得分:4)

我发现这可以这样做:

npm i copy-dynamodb-table