gpt4 book ai didi

javascript - 更改 javascript 属性给出修改规则

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:40:51 24 4
gpt4 key购买 nike

我的类结构如下:

class Player {
constructor(id) {
this.limits.playaces = 1;
this.actions.playaces = 0;
}
}

我想应用一个修改函数,让它看起来像这样

var player = new Player();
player.modifyAction("playaces","++"); //increments playaces from actions
player.modifyAction("playaces","--"); //decrements playaces from actions
player.modifyAction("playaces","+4"); //adds 4 to playaces from actions
player.modifyAction("playaces","-1"); //subtract 1 from playaces from actions

我想避免制作 map ,所以我认为 eval() 是最好的行动方案,但我想知道我是否可以使用词法分析器/解析器而不是使用 eval 并转移到新的对象范例,保持类定义尽可能短。

可以吗?

最佳答案

你在找这样的东西吗?

class Player {
constructor(id) {
this.id = id
this.playaces = 1;
}
incrementPlayaces() {
this.playaces++
console.log(this.playaces)
}
decrementPlayaces() {
this.playaces--
console.log(this.playaces)
}
addPlayaces(val) {
this.playaces += val
console.log(this.playaces)
}
}

let player = new Player('id');

player.incrementPlayaces()
player.decrementPlayaces()
player.addPlayaces(-4)
player.addPlayaces(+5)

关于javascript - 更改 javascript 属性给出修改规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51223884/

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