从技术上讲,你可以通过.toString()
方法获得功能的源代码编辑功能,然后执行字符串操作就可以了使用正则表达式等。但它会非常非常混乱,我不推荐它。
相反,给对象更多的结构。首先分离出右手和左手武器:
var shooter = {
rightHand : function() {},
leftHand : function() {},
fire : function() {}
}
现在让.fire()
方法拍摄(或使用)所有武器:
var shooter = {
rightHandWeapon : function() {},
leftHandWeapon : function() {},
fire : function() {
this.rightHandWeapon();
this.leftHandWeapon();
}
}
现在,上面的代码什么也不做(因为这两个函数什么都不做)这意味着上面的代码适用于手无寸铁的射手。
现在,您可以实现武器功能:
function shotgun() {
/* code to fire shotgun */
}
function handgun() {
/* code to fire handgun */
}
是完整的,我们可以定义以下功能,以及:
function unarmed() {};
现在,您可以通过给他的武器武装的射手:
// Armed with shotgun
shooter.rightHandWeapon = shotgun;
shooter.fire();
// Armed with shotgun and handgun:
shooter.rightHandWeapon = shotgun;
shooter.leftHandWeapon = handgun;
shooter.fire();
// Armed with TWO shotguns:
shooter.rightHandWeapon = shotgun;
shooter.leftHandWeapon = shotgun;
shooter.fire();
// Disarm the shooter:
shooter.rightHandWeapon = unarmed;
shooter.leftHandWeapon = unarmed;
shooter.fire(); // does nothing
我不认为杰森想把这样的枪都捆绑在一起,但是否则它看起来也是个好主意。 – lauriys
我同意,这取决于Jason想要达到的目标(没有足够的关于所有其他实体的信息),也取决于应用程序的大小。如果它会很大,最好考虑架构,但如果它只是一个小应用程序,你可能不需要类和其他东西。 –
澄清。我需要选项,而你的答案提供了这个选项。 –