最近因为学习Laya的原因,重新接触了一下JS
在写状态机的时间突然有一个想法
当我从状态机得到一个样的状态,把他转换方法名,通过得到的方法名,能不能直接调用方法
比方说,当前的状态为TestState,判断TestState()是否存在,如果存在则执行this.TestState()
方法一
通过hasOwnProprety判断
var funcName = "TestFunc";
if (GameManager.prototype.hasOwnProperty(funcName))
{
Tools.log("方法存在");
var func = eval("this." + funcName + "()");
}
else
{
Tools.log("方法不存在")
}
方法二
能过eval
//是否存在指定函数
function isExitsFunction(funcName)
{
try
{
if (typeof(eval(funcName)) == "function")
{
return true;
}
}
catch(e) {}
return false;
}
//是否存在指定变量
function isExitsVariable(variableName)
{
try
{
if (typeof(variableName) == "undefined")
{
//alert("value is undefined");
return false;
}
else
{
//alert("value is true");
return true;
}
}
catch(e) {}
return false;
}
