-1

The instance of this class is created like this:

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

Then, I'm trying to destructure these properties like this:

export default class Example {
  constructor(params) {
    const { prop1, prop2 } = params;
    console.log('params', params);
    console.log('prop1', prop1);
    console.log('prop2', prop2);
  }
}

When I log these values, params returns data, but prop1 and prop2 are undefined, and they didn't properly destructure. Is it possible that the way I'm passing this data to the class won't work?

rpivovar
  • 3,150
  • 13
  • 41
  • 79
  • but you're not passing an object in `new Example`, you're passing two separate anonymous arguments, so `params` just maps to the first argument you passed. There is no object to destructure. If you want named property destructuring, use `new Example(this)`, because then you _are_ passing in an object with named properties that can be unpacked. – Mike 'Pomax' Kamermans Aug 29 '19 at 22:14

3 Answers3

4

Is it possible that the way I'm passing this data to the class won't work?

Yes. Your class constructor expects a single options object with two properties, prop1 and prop2. Your call does however simply pass two argument values. You probably want to use

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

or (if you don't care about other properties getting passed along) just

this.example = new Example(this);

Alternatively, keep your call and declare the constructor as constructor(prop1, prop2), without any object destructuring.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You are passing two different parameters to the function. What is being destructured there is actually the first parameter this.prop1. You have several options:


Pass an object:

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

.

constructor(params) {
    const { prop1, prop2 } = params;

Pass the arguments separately:

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

.

constructor(prop1, prop2) {

Pass an array:

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

.

constructor(params) {
    const [prop1, prop2] = params;

Use arguments

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

.

constructor() {
    const [prop1, prop2] = arguments;
Alvaro
  • 9,247
  • 8
  • 49
  • 76
-1

I would like to suggest passing an array.

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

Like @Bergi said one parameter. If you are looking for more then one param, then:

constructor(...params)

But this wont help you much on destructuring.

Jason T
  • 37
  • 3