Search code examples
javaundefinednashorn

Nashorn ability to pass undefined variables to a function


Here is a piece of very simple piece of Java code that evaluates some JavaScript code:

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'));"
        );
}

When it tries to run the ifExists(someVariableThatIsUndefined, 'this string should be returned') the engine throws a fit saying that someVariableThatIsUndefined is..well undefined which defeats the purpose of the utility method for checking if something is undefined.

Is there any possible way that I could pass 'someVariableThatIsUndefined' to a function that returns that variable if it is defined otherwise return something else.

The only limitation is governed by the params parsed to the engine "-strict, --no-java, --no-syntax-extensions"


Solution

  • you can test function existing or not with

    window['myFunctionName'] !== 'undefined'
    

    or in case of a property

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