4

I am trying ES6 object destructuring inside a constructor hoping to assign value to a member variable. It is not working. Its showing undefined when I am printing the value inside a member function. Its printing correctly if I print inside the constructor.Is this valid?

    class Environment {
        constructor(env) {
            const { name, version } = env
            console.log(name)
        }

        printName() {
            console.log(this.name)
        }
    }
    var obj = { "name": "inst1", "version": "12.2.7" };
    var envObj = new Environment(obj);
    envObj.printName();
KKB
  • 43
  • 3

1 Answers1

6

You can assign destructured properties directly to object props using aliases and a wrapping the expression in parentheses:

class Environment {
    constructor(env) {
        ({ name: this.name, version: this.version } = env);
    }

    printName() {
        console.log(this.name)
    }
}
var obj = { "name": "inst1", "version": "12.2.7" };
var envObj = new Environment(obj);
envObj.printName();

If env contains only the properties that you want (name, version), you can Object#assign directly to this:

class Environment {
    constructor(env) {
        Object.assign(this, env);
    }

    printName() {
        console.log(this.name)
    }
}
var obj = { "name": "inst1", "version": "12.2.7" };
var envObj = new Environment(obj);
envObj.printName();
Ori Drori
  • 183,571
  • 29
  • 224
  • 209