<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	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/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>unitstep.net &#187; functions</title>
	<atom:link href="http://unitstep.net/blog/category/functions/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<lastBuildDate>Mon, 06 Feb 2012 01:23:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>JavaScript functions: First-class objects</title>
		<link>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/</link>
		<comments>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 02:55:05 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[functions]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=806</guid>
		<description><![CDATA[In JavaScript, functions are first-class objects, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript. For example, a function can be created, stored in a variable or even be the return value of another function, as seen below: function getPower(power) { return function(x) { return [...]]]></description>
			<content:encoded><![CDATA[<p>In JavaScript, <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope">functions are first-class objects</a>, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript.  For example, a function can be created, stored in a variable or even be the return value of another function, as seen below:</p>
<pre><code>function getPower(power)
{
  return function(x)
  {
    return Math.pow(x, power);
  }
}

var x3 = getPower(3);
window.alert(x3(3)); // Outputs 27.</code></pre>
<p>In the rather stupid and contrived example above, we make a function <code>getPower()</code> that returns another function which raises the given value to the exponent supplied by calling <code>getPower()</code>.  (This is a bad way to do things for numerous reasons, but is just shown for the sake of providing a simple example)</p>
<p>We then call <code>getPower</code> with a power of 3 and assign the returned function to the variable <code>x3</code>, and the output is as expected.  Defining &#8220;inline&#8221; functions this way and manipulating them is closely associated with the concept of anonymous functions.</p>
<h2>Functions: Copied and passed by reference</h2>
<p>Since functions are objects, and <a href=" http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/">objects are passed and copied <em>by reference</em></a>, <a href="https://developer.mozilla.org/Talk:En/Core_JavaScript_1.5_Guide/Defining_Functions">the behaviour</a> should be fairly straightforward to those familiar with the concept.  Here&#8217;s a quick example of what I&#8217;m talking about.  Since JavaScript functions can be treated just like plain old objects, this means we can attach arbitrary properties to them &#8211; let&#8217;s see how that relates to making a &#8220;copy&#8221; of a function:</p>
<pre><code>function test() {window.alert("A Test");}
f = window.test;
window.test.aProperty = 'Hello!';
window.alert(f.aProperty); // Outputs "Hello!"

f.aProperty = 'Goodbye!';
window.alert(window.test.aProperty); // Outputs "Goodbye!"</code></pre>
<p>The key here is that the expression <code>f = window.test;</code> doesn&#8217;t make a complete copy of the function; instead it just ensures that the variable <code>f</code> will point at the same function object as <code>window.test</code>.  So expressions that modify the underlying function object and its data will reflect in both <code>window.test</code> <strong>and</strong> <code>f</code>.  Just think of those two variables as being different ways of accessing the same underlying data.</p>
<p>But let&#8217;s consider another example: <strong>What happens if we make a copy of a function and then redefine the original?</strong></p>
<pre><code>function test() {window.alert("A Test");}

f = window.test;
f(); // "A Test"

// Redefine the original function.
test = function() {window.alert("A changed test");};

f(); // Still "A Test"!
window.test(); // "A changed test"</code></pre>
<p>The results are a bit strange &#8211; it appears that when we redefine <code>test</code>, the changes <strong>are not reflected</strong> in the copy we created in variable <code>f</code>! Why is this?</p>
<p>Closer inspection yields the following answer: <strong>We were not actually redefining the function pointed to by <code>test</code></strong>.  Instead, we created a new <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function"><code>Function</code></a> object in memory and then &#8220;pointed&#8221; <code>test</code> at this new function.  The old function, formerly referenced by <code>test</code>, is still referenced by the variable <code>f</code> so that is why it continues to invoke that code.</p>
<p>This is illustrated by the following diagrams.  In the first, the original function has been defined and two variables refer to it.</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/javascript-function-1.png" alt="javascript-function-1" title="javascript-function-1" width="272" height="75" class="alignnone size-full wp-image-815" />
</p>
<p>In the second diagram, we have created a new function and altered the variable <code>test</code> to refer to it; however the variable <code>f</code> still refers to the original function.  Thus, the important thing to note is that when using the assignment operator for functions, they are copied by reference.</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/javascript-function-2.png" alt="javascript-function-2" title="javascript-function-2" width="280" height="130" class="alignnone size-full wp-image-816" /><br />
The original function is still referenced by <code>f</code>
</p>
<h2>Where this matters</h2>
<p>This point has relevance when talking about event handlers.  Typically, when we bind functions to a specific events this involves copying a function reference over to some other variable or property.  Whether we directly do this using <a href="http://www.quirksmode.org/js/events_tradmod.html">traditional event registration</a> by using an expression like <code>element.onclick = someFunction</code> or whether it&#8217;s done using jQuery&#8217;s <a href="http://docs.jquery.com/Events">Event Helpers</a>, the effect is the same.</p>
<p>This means that after assigning the event handler, <strong>we cannot simply modify the original function to make changes to how the event handler works</strong>.  This is because when we assign a new function the old one will still be referenced by the event handler.  The proper way to do this at runtime would be simply to register the new function to the event and deregister the old one.</p>
<p>Another way to think of it is that you can often register anonymous functions to events; since they are anonymous you won&#8217;t have a reference to them after you assign them to the event handler so there is no way to modify them after the fact.  This same logic applies equally when assigning non-anonymous functions to events.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

