Is it possible to simulate constants in Javascript using closures?

后端 未结 4 358
余生分开走
余生分开走 2021-01-27 09:24

Is it possible to simulate constants in Javascript using closures? If so, can you please furnish me with an example?

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 09:52

    Firefox and Chrome both support the const keyword. IE does not. So if you need constants and don't need to support IE, const isn't a bad choice. Keep in mind though, neither browser produces a runtime error when a value is assigned to a const; the values merely remains unchanged.

    Otherwise, you must use functions to define constants that cannot be modified:

    function PI() { return 3.14159; }
    
    var area = radius*radius * PI();
    

    Of course, you could just write code that never modifies certain variables, and maybe establish a naming scheme for such variables such that you recognize that they will never need to be modified...

    // note to self: never assign values to variables utilizing all-uppercase name
    var PI = 3.14159;
    

    Another option for "simulating" constants would be to use the property definition functionality available in some browsers to define read-only properties on an object. Of course, since the browsers supporting property definitions don't include IE, that doesn't really help... (note that IE8 does support property definitions after a fashion... but not on JavaScript objects)

    Finally, in very contrived scenarios you might use function arguments as constants (perhaps this is what you were thinking of when you suggested closures?). While they behave as variables, they remain scoped to the function in which they are defined and cannot therefore affect the values held by variables with the same name outside of the function in which they are modified:

    var blah = 3;
    var naw = "nope";
    (function(blah, naw)
    {
      blah = 2;
      naw = "yeah";
      alert(naw + blah); // "yeah2"
    })(blah, naw);
    
    alert(naw + blah); // "nope3"
    

    Note that something similar to this is commonly used by jQuery plugins, but for the opposite reason: jQuery code is usually written using the $ shorthand to refer to the jQuery object, but the library is intended to continue working even if some other code redefines that symbol; by wrapping library and plugin code in anonymous functions with a $ parameter and then passing in jQuery as an argument, the code is isolated from changes other libraries might make to the value of $ later on.


    See also: Are there constants in Javascript?

提交回复
热议问题