JavaScript define
Define a new constant
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 39 4041 42 43 44 4546 47 48 49 5051 52 53 54 5556 57 58 59 6061 62 63 | function define (name, value) { // Define a new constant // // version: 903.3016 // discuss at: http://phpjs.org/functions/define // + original by: Paulo Ricardo F. Santos // + revised by: Andrea Giammarchi (http://webreflection.blogspot.com) // + reimplemented by: Brett Zamir (http://brett-zamir.me) // * example 1: define('IMAGINARY_CONSTANT1', 'imaginary_value1'); // * results 1: IMAGINARY_CONSTANT1 == 'imaginary_value1' var defn, replace, script, that = this, d = this.window.document; var toString = function (name, value) { return 'const ' + name + '=' + ( /^(null|true|false|(\+|\-)?\d+(\.\d+)?)$/.test(value = String(value)) ? value : '"' + replace(value) + '"' ); }; try { eval('const e=1'); replace = function (value){ var replace = { "\x08":"b", "\x0A":"\\n", "\x0B":"v", "\x0C":"f", "\x0D":"\\r", '"':'"', "\\":"\\" }; return value.replace(/\x08|[\x0A-\x0D]|"|\\/g, function (value){ return "\\"+replace[value]; }); }; defn = function (name, value){ if (d.createElementNS) { script = d.createElementNS('http://www.w3.org/1999/xhtml', 'script'); } else { script = d.createElement('script'); } script.type = 'text/javascript'; script.appendChild(d.createTextNode(toString(name, value))); d.documentElement.appendChild(script); d.documentElement.removeChild(script); }; } catch (e){ replace = function (value) { var replace = { "\x0A":"\\n", "\x0D":"\\r" }; return value.replace(/"/g, '""').replace(/\n|\r/g, function (value){ return replace[value]; }); }; defn = (this.execScript ? function (name, value){ that.execScript(toString(name, value), 'VBScript'); }: function (name, value){ eval(toString(name, value).substring(6)); }); } defn(name, value); } |
Examples
Running
1 | define('IMAGINARY_CONSTANT1', 'imaginary_value1'); |
Should result in
1 | IMAGINARY_CONSTANT1 == 'imaginary_value1' |
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 define goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>