Are there constants in JavaScript?

后端 未结 30 2906
抹茶落季
抹茶落季 2020-11-22 08:53

Is there a way to use constants in JavaScript?

If not, what\'s the common practice for specifying variables that are used as constants?

30条回答
  •  日久生厌
    2020-11-22 09:25

    Okay, this is ugly, but it gives me a constant in Firefox and Chromium, an inconstant constant (WTF?) in Safari and Opera, and a variable in IE.

    Of course eval() is evil, but without it, IE throws an error, preventing scripts from running.

    Safari and Opera support the const keyword, but you can change the const's value.

    In this example, server-side code is writing JavaScript to the page, replacing {0} with a value.

    try{
        // i can haz const?
        eval("const FOO='{0}';");
        // for reals?
        var original=FOO;
        try{
            FOO='?NO!';
        }catch(err1){
            // no err from Firefox/Chrome - fails silently
            alert('err1 '+err1);
        }
        alert('const '+FOO);
        if(FOO=='?NO!'){
            // changed in Sf/Op - set back to original value
            FOO=original;
        }
    }catch(err2){
        // IE fail
        alert('err2 '+err2);
        // set var (no var keyword - Chrome/Firefox complain about redefining const)
        FOO='{0}';
        alert('var '+FOO);
    }
    alert('FOO '+FOO);
    

    What is this good for? Not much, since it's not cross-browser. At best, maybe a little peace of mind that at least some browsers won't let bookmarklets or third-party script modify the value.

    Tested with Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9.

提交回复
热议问题