对象解构为 class 属性无效
Object destructuring into class properties not working
这个class的实例是这样创建的:
this.example = new Example(this.prop1, this.prop2);
然后,我尝试像这样解构这些属性:
export default class Example {
constructor(params) {
const { prop1, prop2 } = params;
console.log('params', params);
console.log('prop1', prop1);
console.log('prop2', prop2);
}
}
当我记录这些值时,params
returns 数据,但 prop1
和 prop2
是 undefined
,它们没有正确解构。我将此数据传递给 class 的方式可能行不通吗?
Is it possible that the way I'm passing this data to the class won't work?
是的。您的 class 构造函数需要一个具有两个属性的选项对象,prop1
和 prop2
。但是,您的调用确实只是传递了两个参数值。你可能想使用
this.example = new Example({prop1: this.prop1, prop2: this.prop2});
或者(如果您不关心其他属性的传递)只是
this.example = new Example(this);
或者,保持调用并将构造函数声明为 constructor(prop1, prop2)
,不进行任何对象解构。
我想建议传递一个数组。
this.example = new Example([this.prop1, this.prop2]);
就像@Bergi 说的一个参数。如果您正在寻找不止一个参数,那么:
constructor(...params)
但这对解构没有太大帮助。
您正在向函数传递两个不同的参数。那里被解构的实际上是第一个参数this.prop1
。您有多种选择:
传递一个对象:
this.example = new Example({ prop1: this.prop1, prop2: this.prop2 });
.
constructor(params) {
const { prop1, prop2 } = params;
单独传递参数:
this.example = new Example(this.prop1, this.prop2);
.
constructor(prop1, prop2) {
传递数组:
this.example = new Example([this.prop1, this.prop2]);
.
constructor(params) {
const [prop1, prop2] = params;
this.example = new Example(this.prop1, this.prop2);
.
constructor() {
const [prop1, prop2] = arguments;
这个class的实例是这样创建的:
this.example = new Example(this.prop1, this.prop2);
然后,我尝试像这样解构这些属性:
export default class Example {
constructor(params) {
const { prop1, prop2 } = params;
console.log('params', params);
console.log('prop1', prop1);
console.log('prop2', prop2);
}
}
当我记录这些值时,params
returns 数据,但 prop1
和 prop2
是 undefined
,它们没有正确解构。我将此数据传递给 class 的方式可能行不通吗?
Is it possible that the way I'm passing this data to the class won't work?
是的。您的 class 构造函数需要一个具有两个属性的选项对象,prop1
和 prop2
。但是,您的调用确实只是传递了两个参数值。你可能想使用
this.example = new Example({prop1: this.prop1, prop2: this.prop2});
或者(如果您不关心其他属性的传递)只是
this.example = new Example(this);
或者,保持调用并将构造函数声明为 constructor(prop1, prop2)
,不进行任何对象解构。
我想建议传递一个数组。
this.example = new Example([this.prop1, this.prop2]);
就像@Bergi 说的一个参数。如果您正在寻找不止一个参数,那么:
constructor(...params)
但这对解构没有太大帮助。
您正在向函数传递两个不同的参数。那里被解构的实际上是第一个参数this.prop1
。您有多种选择:
传递一个对象:
this.example = new Example({ prop1: this.prop1, prop2: this.prop2 });
.
constructor(params) {
const { prop1, prop2 } = params;
单独传递参数:
this.example = new Example(this.prop1, this.prop2);
.
constructor(prop1, prop2) {
传递数组:
this.example = new Example([this.prop1, this.prop2]);
.
constructor(params) {
const [prop1, prop2] = params;
this.example = new Example(this.prop1, this.prop2);
.
constructor() {
const [prop1, prop2] = arguments;