gpt4 book ai didi

javascript - 函数构造函数是否支持 `this` 的计算属性?

转载 作者:行者123 更新时间:2023-11-29 17:48:24 26 4
gpt4 key购买 nike

尝试测试类似 ≈ 的东西

> function Computed(name, prop) {
... [this.prop]: name
... };
... // but this doesn't work.

有没有办法正确地做到这一点?

最佳答案

计算属性仅在类主体或对象字面量中起作用,在函数中不起作用(就像普通属性定义一样)。但无论如何你都不需要它们:你可以只使用括号语法在实例上创建属性:

function Computed(name, prop) {
this[prop] = name;
}

关于javascript - 函数构造函数是否支持 `this` 的计算属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46678176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com