JavaScript constant
Given the name of a constant this function will return the constant's associated value
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 | function constant (name) { // Given the name of a constant this function will return the constant's associated value // // version: 1109.2015 // discuss at: http://phpjs.org/functions/constant // + original by: Paulo Freitas // + improved by: Brett Zamir (http://brett-zamir.me) // * example 1: constant('IMAGINARY_CONSTANT1'); // * returns 1: null var clssPos = 0, clssCnst = null; if ((clssPos = name.indexOf('::')) !== -1) { clssCnst = name.slice(clssPos + 2); name = name.slice(0, clssPos); } if (this.window[name] === undefined) { return null; } if (clssCnst) { return this.window[name][clssCnst]; } return this.window[name]; } |
Examples
Running
1 | constant('IMAGINARY_CONSTANT1'); |
Should return
1 | null |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have constant goodness in JavaScript.

Hmm, this one should require get_defined_constants(), no? When I wrote I think that the get_defined_constants() doesn't exist yet, but for now it should be useful to do things like constant('DATE_W3C'). :)
Brett Zamir
21 Jun '10