Javascript class 构造函数,参数用作 object 文字的键

Javascript class constructor with parameter used as key from object literal

标题可能有点混乱,但我有以下问题:

var propertyList = {
    type1: {property1: 1},
    type2: {property1: 2}
}

class Test {
    constructor(typ){
        this.property1 = propertyList.typ.property1;
    }
}

var a = new Test('type1');

代码很漂亮 self-explanatory - 我想设置 property1 属性 of a object 不是通过在构造函数中手动传递值,而是选择propertyList object 文字中的值之一,方法是将其键之一传递给构造函数。我预计当我 运行 上面的代码时, object a 将被创建, property1 值设置为 1。但是我得到的不是 Uncaught TypeError: Cannot read property 'property1' of undefined 错误。当我在构造函数的第一行输入 console.log(typ) 时,它正确地显示传递给构造函数的值是 type1。为什么上面的代码不起作用,能否以某种方式修复?

你的语法有点不对劲。你不能像那样在你的赋值中使用传入的参数 typ 因为代码实际上会在 propertyList 中寻找 属性 typ (比如 propertyList { typ: }).要使用传入的参数,请将其括在方括号中:

this.property1 = propertyList[typ].property1;