Although many programming languages provide the Const keyword to support the declaration of constants, there is no semantic representation of constants in JavaScript. We can declare a variable in full capitalization, indicating that it is actually a constant:
Math.PI; 3.141592653589793math.sqrt2; 1.4142135623730951number.max_value; 1.7976931348623157e+308
Usually this constant is wrapped in objects: for example, math above. To implement the constants required in the program, you can do this:
Constructorvar Widget = function () { //implementation...};//constantswidget.max_height = 320; Widget.max_width = 480;
The same idea allows objects created by literal declaration to have all uppercase attributes. But the implementation above does not prevent the user from changing the value of "constant" (which is actually a variable). To solve this problem, you can declare a specific object that holds constants, such as Consot, and provides a uniform definition of constants and the acquisition of values by using the following 3 methods:
- Set (name, value) defines a constant named name, with value values;
- isDefined (name) checks that a constant named name has not been defined;
- Get (name) Gets the value of the constant named name
In the following const implementation, only constant data of a simple type is supported. Check that the data type is available through hasOwnProperty (), and that the constants have been defined:
var constant = (function () { var constants = {}, Ownprop = Object.prototype.hasOwnProperty, allowed = { s Tring:1, number:1, boolean:1 }, prefix = (math.random () + "_"). Slice (2); return { set:function (name, value) { if (this.isdefined (name)) { return false; } if (!ownprop.call (Allowed, typeof value)) { return false; } Constants[prefix + Name] = value; return true; }, isdefined:function (name) { return Ownprop.call (constants, prefix + name); }, get:function (name) { if (this.isdefined (name)) { return constants[prefix + name]; } return null;}} ;} ());
Check this implementation:
Check if definedconstant.isdefined ("MaxWidth"); false//defineconstant.set ("MaxWidth", 480); true//check againconstant.isdefined ("MaxWidth"); true//attempt to Redefineconstant.set ("MaxWidth", 320); false//is the value still Intact?constant.get ("MaxWidth"); 480
Constants for objects of JavaScript base object creation mode (028)