JavaScript类对象如何使用变量值作为动态属性名赋值
问题核心原因
JavaScript中对象的属性访问有两种语法:
- 点语法:
obj.prop会直接把prop当做固定的属性名字符串,不会解析变量 - 方括号语法:
obj[变量/表达式]会先计算方括号内的值,再把结果作为属性名访问
你当前代码里用了$this.property,所以永远会生成名为property的属性,而不会读取property变量存储的实际值。
修改方案
1. 核心修改
把所有$this.property替换为$this[property]即可实现动态属性名挂载。
2. 附加优化建议
建议重命名你的自定义方法,不要和原生的hasOwnProperty重名,避免覆盖原生方法导致后续逻辑出错,我们这里暂时改名为setRequiredProps为例。
修正后的完整代码
class foob { //other methods etc constructor(externalObj) { this._startValues = externalObj; // 调用自定义方法传入需要确保存在的属性和对应默认值 this.setRequiredProps({ "aKeyINeedToBeCertainHasBeenSet": "a default value if the key >aKeyINeedToBeCertainHasBeenSet< has not been set" }); } setRequiredProps(dynamicObject) { let $this = this; let property; Object.keys(dynamicObject).forEach(function(dynamicObjectKey, index) { property = `_${dynamicObjectKey}`; // 改用方括号语法实现动态属性名赋值 if ($this._startValues.hasOwnProperty(dynamicObjectKey)) { $this[property] = $this._startValues[dynamicObjectKey]; } else { $this[property] = dynamicObject[dynamicObjectKey] } }); } } // 测试调用 const instance = new foob({ "key": "value", "anotherKey": false }); // 输出验证:_aKeyINeedToBeCertainHasBeenSet属性会自动挂载默认值 console.log(instance._aKeyINeedToBeCertainHasBeenSet) // 输出:a default value if the key >aKeyINeedToBeCertainHasBeenSet< has not been set
额外简化方案(可选)
如果要进一步精简代码,可以用空值合并运算符直接替换if-else判断,逻辑完全等价:
$this[property] = $this._startValues[dynamicObjectKey] ?? dynamicObject[dynamicObjectKey];
内容的提问来源于stack exchange,提问作者I try so hard but I cry harder
相关产品推荐
相关产品推荐

