Nashorn 能够将未定义的变量传递给函数

Nashorn ability to pass undefined variables to a function

这是一段非常简单的 Java 代码,用于评估一些 Java 脚本代码:

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, 'this string should be returned') 时,引擎会发出一个提示说 someVariableThatIsUndefined is..well undefined 这违背了实用方法检查是否有东西的目的未定义。

是否有任何可能的方法可以将 'someVariableThatIsUndefined' 传递给一个 return 变量的函数,如果它被定义为其他 return 其他东西。

唯一的限制是由解析到引擎的参数“-strict,--no-java,--no-syntax-extensions”决定的

您可以使用

测试现有或不存在的功能
window['myFunctionName'] !== 'undefined'

或者 属性

this['myPropertyName'] !== 'undefined'