2015-11-23

Nashornでletとconstを使う

1. Nashornのバージョンを確認する

>echo "quit();" | jjs -version
nashorn 1.8.0_66
jjs> quit();
jjs>
>

2. 実行するスクリプト(LetAndConst.js):

try {
    const CONST_VALUE = 100;
    print("CONST_VALUE=${CONST_VALUE}");
    try {
        CONST_VALUE = 200;
    } catch (e) {
        print(e);
    }
    let letValue = CONST_VALUE + 1;
    print("letValue=${letValue}");
    var varValue = letValue + 1;
    print("varValue=${varValue}");
} finally {
    print("typeof CONST_VALUE: " + typeof CONST_VALUE);
    print("typeof letValue: " + typeof letValue);
    print("typeof varValue: " + typeof varValue);
}

3. jjsで実行する(--language=es6オプションが無いので文法エラーが起きた):

>jjs -scripting -fullversion LetAndConst.js
nashorn full version 1.8.0_66-b18
LetAndConst.js:2:1 Expected an operand but found const
    const CONST_VALUE = 100;
    ^
LetAndConst.js:9:5 Expected ; but found letValue
    let letValue = CONST_VALUE + 1;
        ^
LetAndConst.js:13:0 Expected eof but found }
} finally {
^

4. jjsで実行する(--language=es6オプションが有るので実行された):

>jjs -scripting -fullversion --language=es6 LetAndConst.js
nashorn full version 1.8.0_66-b18
CONST_VALUE=100
TypeError: Assignment to constant "CONST_VALUE"
letValue=101
varValue=102
typeof CONST_VALUE: undefined
typeof letValue: undefined
typeof varValue: number

0 件のコメント:

コメントを投稿