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 =。 ..' - 無效的語法 –

相關問題