从Java运行的JS文件中的Object.keys函数

时间:2013-09-03 13:40:20

标签: java javascript rhino

当我尝试在作为Java应用程序运行的JavaScript文件中使用Object.keys函数时,我得到了Exception。

我想使用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

2 个答案:

答案 0 :(得分:3)

Object.keys()是ECMAScript 5功能introduced in Javascript 1.8.5

另一方面,

Rhino is based on Javascript 1.7

所以,不幸的是,你坚持:

for (var i in prices) {
  if (prices.hasOwnProperty(i)) {
    // do stuff
  }
}

答案 1 :(得分:2)

没有为Rhino中的Object类定义此方法。

Rhino documentation州:

  

Rhino包含

     
      
  • JavaScript 1.7的所有功能
  •   

Mozilla JavaScript文档说明Object.keys是:

  

在JavaScript 1.8.5中引入

相同的Object.keys文档包含了如何将其添加到以前版本的JavaScript的示例。