我可以帮您翻译:使用PyV8,我是否能够评估具有默认参数的JavaScript函数?

3
我希望您能够用JavaScript在Python中调用函数。我正在使用PyV8,我可以成功地调用一个函数并打印出结果。然而,如果该函数包含默认参数,则会出现语法错误。
这个是正常工作的。
import PyV8

ctxt = PyV8.JSContext()
ctxt.enter()
ctxt.eval("function example(a){return a;}")
render = ctxt.eval("example('hello');")
print render

然而,当我像这样在示例中包含一个默认参数时:
import PyV8

ctxt = PyV8.JSContext()
ctxt.enter()
ctxt.eval("function example(a = 'hello'){return a;}")
render = ctxt.eval("example();")
print render

我遇到了SyntaxError: SyntaxError: Unexpected token = ( @ 1 : 19 )的错误 -> function example(a = 'hello'){return a;}

希望能得到帮助。

1个回答

2

默认参数是ES6的一个特性。
PyV8不支持ES6语法。您需要使用shim/polyfil

import PyV8

jsFunc = """
function test(msg, name) {
  (msg === undefined) && (msg = 'hello');
  (name === undefined) && (name = 'world');
  return msg + ' ' + name
}
"""


ctxt = PyV8.JSContext()
ctxt.enter()
ctxt.eval(jsFunc)
render1 = ctxt.eval("test();")
render2 = ctxt.eval("test('hi');")
print render1
print render2

输出:

hello world
hi world

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接