Js Object-Oriented Programming: how to define constants?

Source: Internet
Author: User

Javascript has a keyword const, but the current browser does not seem to support it. If you must define some constants, you can actually use closures and anonymous functions to define constants.

For example:

Var Class = (function () {var UPPER_BOUND = 100; // defines the constant var Test ={}; // defines a static method to obtain the constant Test. getUPPER_BOUND = function () {return UPPER_BOUND;} return Test ;})();

Usage:

Var k = Class. getUPPER_BOUND (); alert (k );//

When there are multiple constants: You can also write them like this:

Var Class = (function () {// Private static attributes. var constants = {// defines two constants UPPER_BOUND: 100, LOWER_BOUND:-100} var Test ={}; // defines a static method Test. getConstant = function (name) {// return constants [name];} return Test })();

Usage:

Var k = Class. getConstant ('Upper _ bound'); alert (k );//


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.