这是一段非常简单的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是......未定义的,这违背了实用程序方法的目的,以检查某些内容是否未定义。< / p>
是否有任何可能的方法可以将'someVariableThatIsUndefined'传递给返回该变量的函数(如果已定义,否则返回其他内容。
唯一的限制是由解析为引擎的参数“-strict, - no-java, - no-syntax-extensions”控制
答案 0 :(得分:1)
您可以使用
测试现有或不存在的功能window['myFunctionName'] !== 'undefined'
或属性
this['myPropertyName'] !== 'undefined'