1

我是 JavaScript 新手。在 nashorn 1.8.0_11 中,我看到了以下行为。注意print(x)工作正常,但评估x会导致崩溃。我可以认为这是一个错误吗?如果是这样,这是一个已知的错误吗?

jjs> var x = Object.create(null);
jjs> print(x);
<shell>:1 TypeError: Cannot get default string value
jjs> x;
Exception in thread "main" ECMAScript Exception: TypeError: Cannot get default string value
        at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:56)
        at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:212)
        at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:184)
        at jdk.nashorn.internal.objects.Global.getDefaultValue(Global.java:592)
        at jdk.nashorn.internal.runtime.ScriptObject.getDefaultValue(ScriptObject.java:1257)
        at jdk.nashorn.internal.runtime.JSType.toPrimitive(JSType.java:256)
        at jdk.nashorn.internal.runtime.JSType.toPrimitive(JSType.java:252)
        at jdk.nashorn.internal.runtime.JSType.toStringImpl(JSType.java:993)
        at jdk.nashorn.internal.runtime.JSType.toString(JSType.java:326)
        at jdk.nashorn.tools.Shell.readEvalPrint(Shell.java:449)
        at jdk.nashorn.tools.Shell.run(Shell.java:155)
        at jdk.nashorn.tools.Shell.main(Shell.java:130)
        at jdk.nashorn.tools.Shell.main(Shell.java:109)
4

1 回答 1

1

这正如预期的那样。当您使用“jjs”shell 工具以交互方式评估表达式时,它会将评估的表达式结果转换为字符串以打印相同的结果。此外,“打印”函数在对象上调用 toString 以将它的字符串表示形式打印到控制台。使用 Object.create(null),您正在创建一个原型为 null 的对象(因此不继承 Object.prototype.toString)。此外,您的对象没有具有函数类型值的“toString”属性,因此没有 TypeError。请注意,您也可以使用 v8 shell 进行类似的行为。

V8 版本 3.25.15 [示例外壳]

var x = Object.create(null) x; 打印(x)

于 2014-08-11T04:21:41.533 回答