这是一段非常简单的Java代码,用于评估一些JavaScript代码:
public static class Logger
{
public log(String line)
{
System.out.println(line);
}
}
public static void main(String[] args)
{
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new String[]
{
"-strict",
"--no-java",
"--no-syntax-extensions"
});
engine.put("log", new Logger());
engine.eval(
"var ifExists = function(checkExists, otherwise)" +
"{" +
"if(typeof checkExists !== 'undefined')" +
"{" +
"return checkExists;" +
"}" +
"else" +
"{" +
"return otherwise;" +
"}" +
"};" +
"log.log(ifExists(someVariableThatIsUndefined, 'this string should be returned'));"
);
}
当它尝试运行ifExists(someVariableThatIsUndefined,'应该返回此字符串')时,引擎会抛出一个合适的说法,说someVariableThatIsUndefined为..well undefined,这违背了使用实用程序方法检查是否未定义的目的。
有什么可能的方式可以将'someVariableThatIsUndefined'传递给返回该变量的函数(如果已定义),否则返回其他变量。
唯一的限制是由解析到引擎“ -strict,-no-java,-no-syntax-extensions”的参数控制的
最佳答案
您可以使用以下命令测试现有功能或不存在的功能
window['myFunctionName'] !== 'undefined'
或财产
this['myPropertyName'] !== 'undefined'