1

我想使用ES6解构一个类的构造函数,但得到一个未知的令牌错误。这里有一个例子:ES6:不能解构一个调用构造函数

//进口/服务器/ A-和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; 
    } 
} 

//进口/服务器/ test.js

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

const b = new B('123') 

const FirstName = b.FirstName; 

同样的解构会在外面工作类:

//另一个-test.js

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

回答

4

,我发现这是可以做到像这样:

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

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

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

这将是类似于试图做到这一点'让this._Firstname =。 ..' - 无效的语法 –