ES6:无法在调用构造函数中解构
ES6: Can't Deconstruct inside a call constructor
我正在尝试在 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;
同样的解构将在 class 之外工作:
//另一个-test.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;
}
我发现可以这样做:
constructor(id) {
// make MongoDB call and store inside this variable
({ firstName: this._FirstName } = CollectionName.findOne({userId: id}));
}
我正在尝试在 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;
同样的解构将在 class 之外工作:
//另一个-test.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;
}
我发现可以这样做:
constructor(id) {
// make MongoDB call and store inside this variable
({ firstName: this._FirstName } = CollectionName.findOne({userId: id}));
}