当我尝试Object.keys
在作为 Java 应用程序运行的 JavaScript 文件中使用函数时,出现异常。
我想使用 JS 文件中的一些函数,如下所示:
function calculateProductPrice(orderData)
{
...
k = Object.keys(prices);
for (var i = k.length; i > -1; i--)
{
...
}
...
}
var prices = {
"1":[
99,
106,
113,
...
使用此脚本的 java 代码片段:
Context context = Context.enter();
ScriptableObject scope = context.initStandardObjects();
FileReader fr = new FileReader("script.js");
context.evaluateReader(scope, fr, "<cmd>", 1, null);
Object orderData = Context.javaToJS(new OrderData(), scope);
scope.put("orderData", scope, orderData);
Object result = context.evaluateString(scope, "calculateProductPrice(orderData)", "<cmd>", 1, null);
我得到例外:
Exception in thread "main" org.mozilla.javascript.EcmaError: TypeError: Cannot find function keys in object function Object() { [native code for Object.Object, arity=1] }
. (<cmd>#11)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3654)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3632)
at org.mozilla.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3660)
at org.mozilla.javascript.ScriptRuntime.typeError2(ScriptRuntime.java:3679)
at org.mozilla.javascript.ScriptRuntime.notFunctionError(ScriptRuntime.java:3743)
at org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThisHelper(ScriptRuntime.java:2247)
at org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThis(ScriptRuntime.java:2214)
at org.mozilla.javascript.gen.c1._c1(<cmd>:11)
at org.mozilla.javascript.gen.c1.call(<cmd>)
at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:97)
at org.mozilla.javascript.gen.c2._c0(<cmd>:1)
at org.mozilla.javascript.gen.c2.call(<cmd>)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:398)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3065)
at org.mozilla.javascript.gen.c2.call(<cmd>)
at org.mozilla.javascript.gen.c2.exec(<cmd>)
at org.mozilla.javascript.Context.evaluateString(Context.java:1104)
at net.terraincognita.restapi.service.ScriptEngine.<init>(ScriptEngine.java:65)
at net.terraincognita.restapi.service.ScriptEngine.main(ScriptEngine.java:94)
Java Result: 1