有没有办法在从Rhino调用脚本时在javascript函数中有可选参数?

时间:2017-10-09 23:52:34

标签: javascript rhino

我编写了一个广泛使用默认参数的javascript项目,例如:

function hello(x = true){
    ...
}

现在我想从命令行调用我的代码。我尝试过使用Rhino,Nashorn和Node,但遇到默认参数时都会抛出错误。在Rhino中,错误是:

js: "resource.js", line 6: missing ) after formal parameters
js: function hello(x = true){
js: ..................^
js: "resource.js", line 1: Compilation produced 1 syntax errors.

有没有什么方法可以从命令行调用我的项目而不必重写我的所有代码来摆脱默认参数?

由于

编辑:将版本4中的node.js更新为版本8后,这可以正常工作。我将使用node.js,但我仍然不知道这是否可以在rhino上使用。

1 个答案:

答案 0 :(得分:1)

你总是有办法复制默认参数的行为,但它不像新版本的javascript那样可读。

直接的方式如果你只有一个参数将在你的函数中进行undefined检查,

js> function hello(x){
  >   if (x === undefined) x = 5;
  >   return x;
  > }
js> hello()
5
js> hello(42)
42

另一方面,如果你的函数包含更多参数我建议你使用一个对象作为输入,然后检查一个undefined值,如上所述:

js> function hello(args){                              
  >   if (args.x === undefined) args.x = 5;     
  >   return args.x + "-" + args.y;
  > }
js> hello({y: 12})   
5-12
js> hello({x: 1, y: 42})
1-42