<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
		>
<channel>
	<title>Comments on: How to write constants in javascript</title>
	<atom:link href="http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/</link>
	<description>Advanced katas for javascripters</description>
	<lastBuildDate>Fri, 27 Aug 2010 12:50:09 +0000</lastBuildDate>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
	<item>
		<title>By: Dan Simard</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-935</link>
		<dc:creator>Dan Simard</dc:creator>
		<pubDate>Wed, 14 Jul 2010 20:35:10 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-935</guid>
		<description>That&#039;s a good idea. Just don&#039;t forget the parenthesis : SELECTED() and not SELECTED.</description>
		<content:encoded><![CDATA[<p>That&#39;s a good idea. Just don&#39;t forget the parenthesis : SELECTED() and not SELECTED.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Abeckels</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-934</link>
		<dc:creator>Abeckels</dc:creator>
		<pubDate>Wed, 14 Jul 2010 17:55:12 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-934</guid>
		<description>Umm ... just use a function like a constant...&lt;br&gt;&lt;br&gt;     function SELECTED() { return true; }</description>
		<content:encoded><![CDATA[<p>Umm &#8230; just use a function like a constant&#8230;</p>
<p>     function SELECTED() { return true; }</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Dennis</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-860</link>
		<dc:creator>Dennis</dc:creator>
		<pubDate>Tue, 23 Feb 2010 01:34:44 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-860</guid>
		<description>Taken directly from the reference at: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/const

&quot;const is a Mozilla-specific extension, it is not supported by IE, but has been partially supported by Opera since version 9.0 and Safari.&quot;

Until it is supported by browsers with a total marketshare of say 50%, it might as well not exist, so many thanks to the author and to the posters who shared some interesting approaches to getting the functionality of constants in a language that doesn&#039;t support them.</description>
		<content:encoded><![CDATA[<p>Taken directly from the reference at: <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/const" rel="nofollow">https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/const</a></p>
<p>&#8220;const is a Mozilla-specific extension, it is not supported by IE, but has been partially supported by Opera since version 9.0 and Safari.&#8221;</p>
<p>Until it is supported by browsers with a total marketshare of say 50%, it might as well not exist, so many thanks to the author and to the posters who shared some interesting approaches to getting the functionality of constants in a language that doesn&#8217;t support them.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Dave</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-766</link>
		<dc:creator>Dave</dc:creator>
		<pubDate>Thu, 09 Jul 2009 16:58:28 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-766</guid>
		<description>Haha..  interesting to see how many acutally read the article.  It almost gets to the point that a writer needs to write 500 words of caveats and legal mumbo jumbo before posting.   Hahah..  

Thanks for the great article.  It was quick and cocise. Exactly what I needed when I am frantically looking to finish a project and I want the next best thing to contants.  (pseudo-comments) 
Much thanks.</description>
		<content:encoded><![CDATA[<p>Haha..  interesting to see how many acutally read the article.  It almost gets to the point that a writer needs to write 500 words of caveats and legal mumbo jumbo before posting.   Hahah..  </p>
<p>Thanks for the great article.  It was quick and cocise. Exactly what I needed when I am frantically looking to finish a project and I want the next best thing to contants.  (pseudo-comments)<br />
Much thanks.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Casey</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-724</link>
		<dc:creator>Casey</dc:creator>
		<pubDate>Fri, 06 Mar 2009 05:45:41 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-724</guid>
		<description>@Angela: Haha, you suck! Read up before you post...</description>
		<content:encoded><![CDATA[<p>@Angela: Haha, you suck! Read up before you post&#8230;</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Angela</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-462</link>
		<dc:creator>Angela</dc:creator>
		<pubDate>Mon, 21 Apr 2008 12:23:55 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-462</guid>
		<description>Seems the author may be unaware of const.

More info: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Constants

Hope this helps!</description>
		<content:encoded><![CDATA[<p>Seems the author may be unaware of const.</p>
<p>More info: <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Constants" rel="nofollow">http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Constants</a></p>
<p>Hope this helps!</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Andrea Giammarchi</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-52</link>
		<dc:creator>Andrea Giammarchi</dc:creator>
		<pubDate>Mon, 29 Oct 2007 10:01:55 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-52</guid>
		<description>JavaScript scalar constants: http://webreflection.blogspot.com/2007/10/cow-javascript-define-php-like-function.html</description>
		<content:encoded><![CDATA[<p>JavaScript scalar constants: <a href="http://webreflection.blogspot.com/2007/10/cow-javascript-define-php-like-function.html" rel="nofollow">http://webreflection.blogspot.com/2007/10/cow-javascript-define-php-like-function.html</a></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Dan</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-51</link>
		<dc:creator>Dan</dc:creator>
		<pubDate>Mon, 02 Apr 2007 01:36:24 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-51</guid>
		<description>@Aaron : Thanks for such a detailed comment. I&#039;ll try your techniques and will make a post on them. You got it right, you were filtered as spam by Akismet! ;)

@jon : As Aaron, you did a great job. I&#039;ll try it and write about it...

Thanks to both of you!</description>
		<content:encoded><![CDATA[<p>@Aaron : Thanks for such a detailed comment. I&#8217;ll try your techniques and will make a post on them. You got it right, you were filtered as spam by Akismet! <img src='http://www.javascriptkata.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>@jon : As Aaron, you did a great job. I&#8217;ll try it and write about it&#8230;</p>
<p>Thanks to both of you!</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Jon</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-50</link>
		<dc:creator>Jon</dc:creator>
		<pubDate>Sun, 01 Apr 2007 01:30:49 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-50</guid>
		<description>Firefox will let you define constants in several ways, but you can at least protect your constants.
The following should work in IE, but I don&#039;t have a copy around to test with:

function defineConstant( classType, constName, value ) {

	if( classType.prototype.__defineGetter__ != undefined ) {
		function get() {
			return value;
		}
		// Firefox lets us make real constants!
		classType.prototype.__defineGetter__( constName, get );
		classType.prototype.__defineSetter__( constName, function() {} );
	} else {

	if( classType.prototype._consts == undefined ) {
			classType.prototype._consts = new Array();
		}
		classType.prototype._consts.push( function() {
			this.watch( constName, function( property, oldValue, newValue ) {
				alert(&quot;Attempting to change value of constant property: &quot; + property + &quot; to value: &quot; + newValue );
				throw new Error( &quot;Attempting to change value of constant property: &quot; + property + &quot; to value: &quot; + newValue  );
			});
		});
		classType.prototype[constName] = value;
		if( classType.prototype._createConsts == undefined ) {
			classType.prototype._createConsts = function() {
				if( this._consts == undefined ) {
					return;
				}
				for( var x = 0; x &lt; this._consts.length; x++ ) {
					this._consts[x].call( this );
				}
			};
		}
	}
}

Object.prototype._createConsts = function() {
	if( this._consts == undefined ) {
		return;
	}
	alert(&quot;Defining constants&quot;);

	for( var x = 0; x &lt; this._consts.length; x++ ) {
		this._consts[x].call( this );
	}
}

function myClass() {
	this.NON_CONST_ID=42;
	this._createConsts();

}

defineConstant( myClass, &quot;CONST_ID&quot;, 42 );
defineConstant( myClass, &quot;ANOTHER_CONST&quot;, 42 );</description>
		<content:encoded><![CDATA[<p>Firefox will let you define constants in several ways, but you can at least protect your constants.<br />
The following should work in IE, but I don&#8217;t have a copy around to test with:</p>
<p>function defineConstant( classType, constName, value ) {</p>
<p>	if( classType.prototype.__defineGetter__ != undefined ) {<br />
		function get() {<br />
			return value;<br />
		}<br />
		// Firefox lets us make real constants!<br />
		classType.prototype.__defineGetter__( constName, get );<br />
		classType.prototype.__defineSetter__( constName, function() {} );<br />
	} else {</p>
<p>	if( classType.prototype._consts == undefined ) {<br />
			classType.prototype._consts = new Array();<br />
		}<br />
		classType.prototype._consts.push( function() {<br />
			this.watch( constName, function( property, oldValue, newValue ) {<br />
				alert(&#8220;Attempting to change value of constant property: &#8221; + property + &#8221; to value: &#8221; + newValue );<br />
				throw new Error( &#8220;Attempting to change value of constant property: &#8221; + property + &#8221; to value: &#8221; + newValue  );<br />
			});<br />
		});<br />
		classType.prototype[constName] = value;<br />
		if( classType.prototype._createConsts == undefined ) {<br />
			classType.prototype._createConsts = function() {<br />
				if( this._consts == undefined ) {<br />
					return;<br />
				}<br />
				for( var x = 0; x &lt; this._consts.length; x++ ) {<br />
					this._consts[x].call( this );<br />
				}<br />
			};<br />
		}<br />
	}<br />
}</p>
<p>Object.prototype._createConsts = function() {<br />
	if( this._consts == undefined ) {<br />
		return;<br />
	}<br />
	alert(&#8220;Defining constants&#8221;);</p>
<p>	for( var x = 0; x &lt; this._consts.length; x++ ) {<br />
		this._consts[x].call( this );<br />
	}<br />
}</p>
<p>function myClass() {<br />
	this.NON_CONST_ID=42;<br />
	this._createConsts();</p>
<p>}</p>
<p>defineConstant( myClass, &#8220;CONST_ID&#8221;, 42 );<br />
defineConstant( myClass, &#8220;ANOTHER_CONST&#8221;, 42 );</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Aaron Faanes</title>
		<link>http://www.javascriptkata.com/2007/03/28/how-to-write-constants-in-javascript/comment-page-1/#comment-49</link>
		<dc:creator>Aaron Faanes</dc:creator>
		<pubDate>Sat, 31 Mar 2007 13:55:23 +0000</pubDate>
		<guid isPermaLink="false">http://javascriptkata.timmyontime.com/?p=17#comment-49</guid>
		<description>A way to solve this would be through closures. A closure is when a function is defined within another function, the variables that existed in the parent are accessible to the child. For example:

function foo() {
var blah = 2;
return function bar() { return blah; }
}
var x = foo();
alert(x() === 2); // You could also use console.log(x() === 2); here if you&#039;re sane and using firefox.

This is initially very confusing, but understanding it allows many things that would be difficult in other languages, to be very easy here. I&#039;ll first hit the immediate example:

function TheClass() {
var CONST_VALUE = 42;
this.CONST_VALUE = function() { return CONST_VALUE; }
}

Through a closure, we&#039;re able to get what you&#039;re looking for - a constant value. The compromise is now we have to call it, and we&#039;re creating it every time the class is instantiated. For a number, this cost is minimal, and I figure if one needs constness, he&#039;ll be willing to drop in a () here and there.

We could (for purely rambling- and academic purposes) extend this example, so that we don&#039;t want it to be const, but just private.

function TheClass() {
var private_foo = 42;
this.get_foo() { return private_foo; }
this.set_foo(foo) { private_foo = foo; }
}

So now, we can ensure that foo is only changed from our accessor methods. Since it&#039;s made per class, we&#039;re also guaranteed that it&#039;s unique to each instance.

A static constant value can also be achieved, albeit not as elegantly. The code would look something like this:

function TheClass() {
 // ...
}

(function() {
var const_value = 42;
TheClass.const_value = function() { return const_value; }
})();

Once again, we&#039;re able to, through closures, have a true constant value. We could have had this in the global space, but that is evil, and also removes our guarantee since our const_value would be accessible globally, so an anonymous function that&#039;s immediately called does the trick.

This isn&#039;t nearly as clear as it could be with a &quot;const&quot; keyword, but Javascript tends to side with flexibility in these matters.

As far as an enum goes, I&#039;ve worked it out a bit. Usually, I use an enum so that they can be easily switched:

switch(this.size) {
case Sizes.BIG:
// ...
case Sizes.MEDIUM:
// ...
}

You can, however, use strings in switches (Something that I up till recently never considered trying), alleviating the ugliness of a chain of if...elses:
switch(this.size) {
case &quot;big&quot;:
// ...
case &quot;medium&quot;:
// ...
}

This means that if you&#039;re concerned about enums changing, then this drops literals where there should be constants, potentially causing problems. In the end, there&#039;s not a very good, elegant way of doing a large number of these hacks to get familiar behavior. It&#039;s however, not too hard to wrap this stuff in a few small functions:

function constant(value) {
return function() { return value; }
}

Such that you could do:

function TheClass() {
this.const_value = constant(42);
}

Which is definitely prettier. Also works for our private, static stuff.

TheClass.const_value = constant(42);

Similarly, a quick enum function removes the common bug of 1,2,3,5:

function enumerate(values) {
var obj = {};
for(var i in values) obj[values[i]] = parseInt(i);
return obj;
}
enumerate(&quot;small medium large&quot;.split(&quot; &quot;)); // I&#039;m lazy and dont like [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;,&quot;&quot;]

Which is just a quick reverse of the keys to values.

One danger here is omitting parseInt. for(var i in obj) makes i be the name of the key, and since Javascript converts all keys to strings, i will be &quot;0&quot;. If you end up using === (which you should, since it&#039;s a little faster and alleviates some bugs with type coercion), then this will cause unexpected failures (As 0 !== &quot;0&quot; but &quot;0&quot; == 0. Go figure.)

One thing that I&#039;ve heard discouraged is the use of capitals to signify constants. Since a malicious, or really confused, programmer could change the function definition of our class, it&#039;s still not flawlessly constant. And on top of that, as someone pointed out, it&#039;s not constant if you have it in the class itself as a value, and CONSTANT() makes it look like it&#039;s a constant function, which, while true, seems redundant if you&#039;re hailing from a language not as free as Javascript. But this is mostly a philosophical issue of what feels right and comfortable.

I hope this helps and isn&#039;t filtered as spam :)

 - Aaron</description>
		<content:encoded><![CDATA[<p>A way to solve this would be through closures. A closure is when a function is defined within another function, the variables that existed in the parent are accessible to the child. For example:</p>
<p>function foo() {<br />
var blah = 2;<br />
return function bar() { return blah; }<br />
}<br />
var x = foo();<br />
alert(x() === 2); // You could also use console.log(x() === 2); here if you&#8217;re sane and using firefox.</p>
<p>This is initially very confusing, but understanding it allows many things that would be difficult in other languages, to be very easy here. I&#8217;ll first hit the immediate example:</p>
<p>function TheClass() {<br />
var CONST_VALUE = 42;<br />
this.CONST_VALUE = function() { return CONST_VALUE; }<br />
}</p>
<p>Through a closure, we&#8217;re able to get what you&#8217;re looking for &#8211; a constant value. The compromise is now we have to call it, and we&#8217;re creating it every time the class is instantiated. For a number, this cost is minimal, and I figure if one needs constness, he&#8217;ll be willing to drop in a () here and there.</p>
<p>We could (for purely rambling- and academic purposes) extend this example, so that we don&#8217;t want it to be const, but just private.</p>
<p>function TheClass() {<br />
var private_foo = 42;<br />
this.get_foo() { return private_foo; }<br />
this.set_foo(foo) { private_foo = foo; }<br />
}</p>
<p>So now, we can ensure that foo is only changed from our accessor methods. Since it&#8217;s made per class, we&#8217;re also guaranteed that it&#8217;s unique to each instance.</p>
<p>A static constant value can also be achieved, albeit not as elegantly. The code would look something like this:</p>
<p>function TheClass() {<br />
 // &#8230;<br />
}</p>
<p>(function() {<br />
var const_value = 42;<br />
TheClass.const_value = function() { return const_value; }<br />
})();</p>
<p>Once again, we&#8217;re able to, through closures, have a true constant value. We could have had this in the global space, but that is evil, and also removes our guarantee since our const_value would be accessible globally, so an anonymous function that&#8217;s immediately called does the trick.</p>
<p>This isn&#8217;t nearly as clear as it could be with a &#8220;const&#8221; keyword, but Javascript tends to side with flexibility in these matters.</p>
<p>As far as an enum goes, I&#8217;ve worked it out a bit. Usually, I use an enum so that they can be easily switched:</p>
<p>switch(this.size) {<br />
case Sizes.BIG:<br />
// &#8230;<br />
case Sizes.MEDIUM:<br />
// &#8230;<br />
}</p>
<p>You can, however, use strings in switches (Something that I up till recently never considered trying), alleviating the ugliness of a chain of if&#8230;elses:<br />
switch(this.size) {<br />
case &#8220;big&#8221;:<br />
// &#8230;<br />
case &#8220;medium&#8221;:<br />
// &#8230;<br />
}</p>
<p>This means that if you&#8217;re concerned about enums changing, then this drops literals where there should be constants, potentially causing problems. In the end, there&#8217;s not a very good, elegant way of doing a large number of these hacks to get familiar behavior. It&#8217;s however, not too hard to wrap this stuff in a few small functions:</p>
<p>function constant(value) {<br />
return function() { return value; }<br />
}</p>
<p>Such that you could do:</p>
<p>function TheClass() {<br />
this.const_value = constant(42);<br />
}</p>
<p>Which is definitely prettier. Also works for our private, static stuff.</p>
<p>TheClass.const_value = constant(42);</p>
<p>Similarly, a quick enum function removes the common bug of 1,2,3,5:</p>
<p>function enumerate(values) {<br />
var obj = {};<br />
for(var i in values) obj[values[i]] = parseInt(i);<br />
return obj;<br />
}<br />
enumerate(&#8220;small medium large&#8221;.split(&#8221; &#8220;)); // I&#8217;m lazy and dont like ["", "", "", "",""]</p>
<p>Which is just a quick reverse of the keys to values.</p>
<p>One danger here is omitting parseInt. for(var i in obj) makes i be the name of the key, and since Javascript converts all keys to strings, i will be &#8220;0&#8243;. If you end up using === (which you should, since it&#8217;s a little faster and alleviates some bugs with type coercion), then this will cause unexpected failures (As 0 !== &#8220;0&#8243; but &#8220;0&#8243; == 0. Go figure.)</p>
<p>One thing that I&#8217;ve heard discouraged is the use of capitals to signify constants. Since a malicious, or really confused, programmer could change the function definition of our class, it&#8217;s still not flawlessly constant. And on top of that, as someone pointed out, it&#8217;s not constant if you have it in the class itself as a value, and CONSTANT() makes it look like it&#8217;s a constant function, which, while true, seems redundant if you&#8217;re hailing from a language not as free as Javascript. But this is mostly a philosophical issue of what feels right and comfortable.</p>
<p>I hope this helps and isn&#8217;t filtered as spam <img src='http://www.javascriptkata.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p> &#8211; Aaron</p>
]]></content:encoded>
	</item>
</channel>
</rss>
