节点js中构造函数内部的对象解构以将值分配给成员变量不起作用

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

我正在尝试在构造函数中解构 ES6 对象,希望为成员变量赋值。它不工作。当我在时它显示未定义 在成员函数中打印值。如果我在 constructor.Is 内打印,它的打印正确吗?

    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();

您可以使用 aliases 将解构的属性直接分配给对象道具,并将表达式括在括号中:

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();

如果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();