Javascript 对象分解为类属性不起作用

Javascript 对象分解为类属性不起作用,javascript,object,ecmascript-6,es6-class,destructuring,Javascript,Object,Ecmascript 6,Es6 Class,Destructuring,该类的实例如下所示: this.example=新示例(this.prop1,this.prop2); 然后,我尝试像这样分解这些属性: 导出默认类示例{ 构造函数(参数){ 常量{prop1,prop2}=params; console.log('params',params); console.log('prop1',prop1); console.log('prop2',prop2); } } 当我记录这些值时,params返回数据,但是prop1和prop2是未定义的,并且它们没有正

该类的实例如下所示:

this.example=新示例(this.prop1,this.prop2);
然后,我尝试像这样分解这些属性:

导出默认类示例{
构造函数(参数){
常量{prop1,prop2}=params;
console.log('params',params);
console.log('prop1',prop1);
console.log('prop2',prop2);
}
}
当我记录这些值时,
params
返回数据,但是
prop1
prop2
未定义的
,并且它们没有正确地解构。我将这些数据传递给类的方式是否可能不起作用

我将这些数据传递给类的方式是否可能不起作用

对。类构造函数需要一个具有两个属性的选项对象,
prop1
prop2
。但是,您的调用只传递两个参数值。您可能想使用

this.example = new Example({prop1: this.prop1, prop2: this.prop2});
或者(如果你不关心其他财产的传承)只是


或者,保持调用并将构造函数声明为
构造函数(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 });


分别传递参数:

this.example = new Example(this.prop1, this.prop2);
this.example = new Example(this.prop1, this.prop2);


传递数组:

this.example = new Example([this.prop1, this.prop2]);


使用


但是在
new Example
中没有传递对象,而是传递两个独立的匿名参数,因此
params
只映射到传递的第一个参数。没有要分解的对象。如果您想要命名属性的解构,请使用
新示例(this)
,因为这样您将传入一个具有可以解包的命名属性的对象。
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;