gpt4 book ai didi

javascript - ES6 : Can't Deconstruct inside a call constructor

转载 作者:行者123 更新时间:2023-11-30 07:21:00 26 4
gpt4 key购买 nike

我正在尝试在类构造函数中使用 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;

同样的解构将在类之外工作:

//另一个测试.js

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

最佳答案

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

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

关于javascript - ES6 : Can't Deconstruct inside a call constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44212424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com