gpt4 book ai didi

javascript - 通过传递的变量引用对象的函数属性

转载 作者:行者123 更新时间:2023-12-02 18:47:09 26 4
gpt4 key购买 nike

我对 JavaScript 和一般编程都很陌生。这个问题是在RPG的背景下提出的。我在战斗函数中有一个 Angular 色对象,尝试根据a)预定义的 Angular 色类和b)输入调用能力函数:

// player example
var player = {
this.pClass = 0; // denotes character class; could also be 1 or 2
}

// ability list
var ability = {
// first character class
0: {
1: function() {some action;},
2: function() {some other action;}
},
// second character class
1: {
// same deal here
}
};

var input = prompt("Enter an action number:");

我希望能够通过传递玩家类别和所选号码来调用操作,例如:

ability.{player.pClass}.{input}();

我是否以正确的方式处理这个问题?如果可能的话,我不想为每个选项迭代 if...else if 语句。感谢您的帮助。

最佳答案

您可以使用方括号访问对象的属性:

var abilities = {
fireball: function() { ... }
};

abilities["fireball"];
abilities.fireball; // equivalent, but only if the index is a valid js identifier

虽然您可以使用数字索引,但我建议采用更面向对象的方式:

// define what a player is and can do
var Player = function(pClass) {
this.pClass= pClass;
};

Player.prototype.useAbility = function(name) {
if (this.pClass.abilities[name]) { // make sure this player can use the ability
this.pClass.abilities[name]();
}
};

// define what a class is
var PClass = function(name) {
this.name = name;
this.abilities = {};
};

// define "mage" class
PClass.mage = new PClass("mage");
PClass.mage.abilities["fireball"] = function() { ... }
PClass.mage.abilities["hex"] = function() { ... }

PClass.warrior = new PClass("warrior");
PClass.warrior.abilities["riposte"] = function() { ... }

// create a new player
var bartTheFearsome = new Player(PClass.mage);
bartTheFearsome.useAbility("fireball");
bartTheFearsome.useAbility(prompt("enter ability name")); // enter "fireball" or "hex"

如果您是(面向对象)编程新手,here这是一个很好的起点。

关于javascript - 通过传递的变量引用对象的函数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16247612/

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