I am trying to call a function from JavaScript in python. I am using PyV8 and I can successfully call a function and print out the result. However, if the function contains a default parameter then I get a Syntax Error.
This works fine.
import PyV8
ctxt = PyV8.JSContext()
ctxt.enter()
ctxt.eval("function example(a){return a;}")
render = ctxt.eval("example('hello');")
print render
However, when I make example contain a default parameter like this:
import PyV8
ctxt = PyV8.JSContext()
ctxt.enter()
ctxt.eval("function example(a = 'hello'){return a;}")
render = ctxt.eval("example();")
print render
I get SyntaxError: SyntaxError: Unexpected token = ( @ 1 : 19 ) -> function example(a = 'hello'){return a;}
Any help is appreciated.
Default arguments are a feature of ES6.
PyV8 doesn't support ES6 syntax. You need to use a 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
Prints:
hello world
hi world