object destructing inside constructor in nodejs to assign values to member variable not working

KKB*_*KKB 4 node.js ecmascript-6 object-destructuring

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();
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 5

您可以使用别名和括号中的表达式将解构属性直接分配给对象道具:

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();
Run Code Online (Sandbox Code Playgroud)

如果env只包含您想要的属性(名称、版本),您可以直接将Object#assign 分配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();
Run Code Online (Sandbox Code Playgroud)