在Nashorn中启用了乐观类型的嵌套对象中的奇怪行为(属性设置为零)

时间:2016-09-28 23:38:53

标签: javascript java java-8 nashorn

这是在JDK 8u102上。我看到奇怪的行为,当乐观类型设置为true时,对象的某些特性被设置为零。这是一个演示行为的jjs脚本:

var config = {};

var creativeDetails = {
    fanpage_id: config.fanpage_id || "293867224112667",
    image_url: config.image_url || "http://some.url",
    title: config.title || "Ad Title",
    description: config.description || "Ad Description",
    link_description: config.link_description || "Link Description",
    call_to_action: config.call_to_action || "LEARN_MORE",
    destination_url: "http://some.url",
    link_body: config.link_body || "Link Body"
};

var linkData = {
    call_to_action: {
        type: creativeDetails.call_to_action,
        value:{
            link_caption: creativeDetails.link_description,
            link: creativeDetails.destination_url
        }
    },
    link: creativeDetails.destination_url,
    picture: creativeDetails.image_url,
    message: creativeDetails.description,
    name: creativeDetails.title
};

print(JSON.stringify(linkData, null, 4) + "\n");

使用jjs运行此操作而不带任何参数会给出:

{
    "call_to_action": {
        "type": "LEARN_MORE",
        "value": {
            "link_caption": "Link Description",
            "link": "http://some.url"
        }
    },
    "link": "http://some.url",
    "picture": "http://some.url",
    "message": "Ad Description",
    "name": "Ad Title"
}

而使用jjs --optimistic-types=true运行它会给出:

{
    "call_to_action": {
        "type": "LEARN_MORE",
        "value": {
            "link_caption": "Link Description",
            "link": "http://some.url"
        }
    },
    "link": 0,
    "picture": 0,
    "message": 0,
    "name": 0
}

||表达式更改为三元组并未改变行为。但是,在初始化creativeDetails对象之前,以任何方式引用linkData对象的属性(例如,将其分配给另一个变量或将其打印出来),最终会打印出预期的结果。

奇怪的是,嵌套对象获取正确的值,但外部对象却没有。如果您正在使用有问题的对象属性来初始化嵌套对象的属性,则只会显示此行为。例如,以下代码不会导致此问题:

var linkData = {
    link: creativeDetails.destination_url,
    picture: creativeDetails.image_url,
    message: creativeDetails.description,
    name: creativeDetails.title
};

我知道Nashorn的乐观类型通过假设某事物的类型是int然后逐步降级到Object来工作。所以它可能与此有关,但我不确定这是怎么发生的。有没有人见过这种行为?

1 个答案:

答案 0 :(得分:0)

这是Nashorn中的一个错误,一直是resolved