<?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/"
	>

<channel>
	<title>unitstep.net &#187; prototype</title>
	<atom:link href="http://unitstep.net/blog/category/prototype/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<pubDate>Tue, 30 Dec 2008 19:37:22 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JavaScript and inheritance</title>
		<link>http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/</link>
		<comments>http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/#comments</comments>
		<pubDate>Fri, 25 Jan 2008 03:22:35 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[guides]]></category>

		<category><![CDATA[inheritance]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/</guid>
		<description><![CDATA[JavaScript has a complicated history.  The name itself seems to indicate a relationship to Java, when in fact, the two languages share little in common except for a common syntax relationship by way of C.  Add to this the myriad of browser incompatibilities and numerous examples of bad usage, and you have what [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript has a complicated history.  The <a href="http://en.wikipedia.org/wiki/Javascript#History_and_naming">name itself</a> seems to indicate a relationship to Java, when in fact, the two languages share little in common except for a common syntax relationship by way of C.  Add to this the myriad of browser incompatibilities and numerous examples of bad usage, and you have what is perhaps the world&#8217;s least understood popular programming language.  (I had to add the &#8216;popular&#8217; qualifier, since I am sure there are some esoteric languages out there that only a handful of people know)</p>
<p>This is why inheritance in JavaScript is probably one of the least understood concepts.  While languages like Java have well-defined constructs for inheritance, the topic is of less importance with JavaScript.  In many situations, you&#8217;ll never have to deal with these aspects when programming in JavaScript, simply because it isn&#8217;t required for a lot of client side scripts.  However, for larger-scale web applications, applying object-oriented principles to your code may make it easier to design, improve and maintain.</p>
<p>There have been <a href="http://javascript.crockford.com/inheritance.html">many</a> <a href="http://javascript.crockford.com/prototypal.html">articles</a> <a href="http://20bits.com/2007/03/08/the-philosophy-of-javascript/">written</a> about inheritance in JavaScript and how it can and should be done.  You really don&#8217;t need to read mine to gain an understanding.  Rather, I&#8217;m just going to write about what I&#8217;ve learned, the process I went through and the experience I&#8217;ve gained along the way. </p>
<h3>It&#8217;s all new(s) to me</h3>
<p>If you come from a Java background, you&#8217;ll be no stranger to the <code>new</code> keyword.  Using it allows you to instantiate a new instance of an object from its class by calling its constructor.  The keyword also makes a lot of sense, since you&#8217;re creating a &#8216;new&#8217; object.</p>
<p>JavaScript also has a <code>new</code> keyword, but it doesn&#8217;t do quite the same thing as its Java counterpart, though at first the effects might seem similar.  This is one of the main reasons why JavaScript inheritance tends to be poorly understood.  </p>
<p>Consider the following example.</p>
<pre><code>function Foo(name)
{
  this.name = name;
}

var fooObject = new Foo('I am foo');</code></pre>
<p>If you&#8217;re familiar with Java or JavaScript, this example is fairly straightforward.  In the prototype-based JavaScript, <a href="http://en.wikipedia.org/wiki/Javascript#Prototype-based_features">functions can serve as object constructors</a> in somewhat the same manner as a constructor in Java.  However, <code>Foo</code> in the above example is not a class, since classes do not exist in JavaScript.  So, if <code>Foo</code> is not a class, what exactly happens when the statement <code>var fooObject = new Foo('I am foo')</code> is executed?</p>
<h3>Taking a step back</h3>
<p>Before we dive into the details, I&#8217;ll explain the concepts of a prototype-based language as it applies to JavaScript.  I mentioned above that JavaScript does not use classes like Java does.  This basically means that new objects are not created from instantiation of classes, but rather inherit from existing objects.  Thus, there is no &#8220;class hierarchy&#8221; but rather just an object hierarchy.  </p>
<p>In JavaScript, all objects are descended from the built-in <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Object"><code>Object</code></a> type.  This is similar to how all Java classes implicitly have the Object class as a superclass.  In JavaScript, instead of extending classes, you can inherit by manipulating the <code>prototype</code> property on a type; that is, the <code>prototype</code> property on the function you are using to create an object.  Let&#8217;s see some code to straighten things out.</p>
<pre><code>function Foo(name)
{
  this.name = name;
}
<strong>Foo.prototype.getName = function()
{
  alert(this.name);
}</strong>

var fooObject = new Foo('I am foo');
<strong>fooObject.getName(); // Will alert with 'I am foo'</strong></code></pre>
<p>This example is identical to the first one, except for the lines that are emphasized.  Here, I&#8217;ve set the <code>getName</code> property on the <code>prototype</code> property of <code>Foo</code> equal to a reference to a Function object.  This is effectively the same as defining a method for a class, since any object created from that type can call the method <code>getName()</code> on itself to return the proper value.  But what exactly is happening, and what&#8217;s the deal with the <code>prototype</code> property?</p>
<h3>More new(s)</h3>
<p>In JavaScript, the <code>new</code> keyword actually accomplishes a few things.  When you execute an expression such as <code>var fooObject = new Foo('I am foo')</code>, here&#8217;s exactly what happens.</p>
<ol>
<li>
First, a new generic object is created.  This object is the same as if you created the object using the statement <code>new Object()</code>, using JavaScript&#8217;s <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Object">built in Object type</a>.
</li>
<li>
The constructor function, that is, the function <code>Foo()</code>, is then called with the <code>this</code> keyword set to reference the newly-created object.  The parameters supplied are also passed to the constructor function, in this case, the string &#8220;I am foo&#8221;.  If you&#8217;re familiar with <a href="/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/">context</a>, this is equivalent to:</p>
<pre><code>var fooObject = new Object();
Foo.call(fooObject, 'I am foo');</code></pre>
<p>Thus, the code in <code>Foo()</code> sets a property called <code>name</code> equal to the supplied string.  Up to this point, things are the same as if you had created a new object and then manually set the <code>name</code> property yourself.  The next step is where things change.
</li>
<li>
The last step is where inheritance takes effect.  The constructor function, in addition to executing the specified code above, also sets an internal property called <code>__proto__</code> equal to the value of <code>Foo.prototype</code>.  This is how the new object inherits from the old one.</p>
<p>When you call a property on <code>fooObject</code> now, JavaScript will first check to see if the object has a local value for it.  In this case, the only local property is <code>name</code>. (Besides the internal and implicitly set <code>__proto__</code> property.  However, if it does not exist locally, it will check to see if the property exists under the object referenced by the <code>__proto__</code> property.  In this case, the <code>getName()</code> method exists under here.
</li>
</ol>
<p>Where things get confusing is because of how the <code>new</code> keyword is used.  Perhaps the designers of JavaScript wanted to use a keyword familiar to Java programmers so as to ease the transition to a new language that sounded so similar.  While it accomplishes a similar goal and for the most part you can consider the action to be almost the same, the use of the <code>new</code> keyword conceals the true meaning of prototype-based inheritance in JavaScript.  This ends up causing more confusion when you start digging into code.</p>
<h3>We&#8217;re all the same</h3>
<p>Suppose you created multiple objects from the <code>Foo()</code> constructor, called <code>fooObject1</code>, <code>fooObject2</code> and <code>fooObject3</code>,   In one fell swoop, you could add a new method to all of these objects without having to recreate them.  This is because of the <code>prototype</code> property.  Because each object contains a reference to <code>Foo.prototype</code>, adding a new method here will allow all objects access to it.  For example:</p>
<pre><code>Foo.prototype.yellName = function()
{
  alert(this.name.toUpperCase());
}
var fooObject3 = new Foo('I am Foo 3!');
fooObject3.yellName(); // alerts 'I AM FOO 3!'</code></pre>
<p>This adds another method to all <code>Foo</code>-constructed objects allowing them to &#8220;yell&#8221; their names.</p>
<h3>Extending Types</h3>
<p>I mentioned inheritance above but with just one type definition, the principles weren&#8217;t too clear.  Suppose we decided to extend our <code>Foo</code> &#8220;class&#8221; - how exactly would this work?  First, you need to define the child type and then set its <code>prototype</code> value to a new object of the parent type.  An example:</p>
<pre><code>function FooChild(childName)
{
  Foo.call(this, 'I am a child of Foo and my name is ' + childName);
}
FooChild.prototype = new Foo('');

var fooChildObject = new FooChild('Barbar');
fooChildObject.getName(); // Will alert with 'I am a child of Foo and my name is Barbar'</code></pre>
<p>Let&#8217;s break down what&#8217;s going on here.</p>
<ol>
<li>
First, we define a new constructor called <code>FooChild</code>.  In it, we <code>call</code> the parent constructor function with the context set to the current object.  This allows the <code>name</code> property to be set on the object during creation since that&#8217;s what the parent does.
</li>
<li>
Then, we set the <code>prototype</code> property equal to a new object that&#8217;s an instance of <code>Foo</code>.  This is what allows all of the child objects to have access to the parent&#8217;s properties, such as the <code>getName()</code> method.
</li>
</ol>
<h3>A few more details</h3>
<p>JavaScript provides two special operators for dealing with types and objects.  One is called <code>instanceof</code> and the other is <code>typeof</code>.  The latter, <code>typeof</code>, is less useful since it only deals with built-in JavaScript types.</p>
<p>The <code>typeof</code> operator returns the current variable&#8217;s type, but is limited to predefined types.  For example, <code>typeof fooChildObject</code> or <code>typeof fooObject</code> both return a string with the contents of &#8220;object&#8221;.  Thus, differentiating between the two is impossible.  More information can be found <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Special_Operators:typeof_Operator">at the Mozilla Developer Center</a>.</p>
<p>The <code>instanceof</code> operator is more interesting.  It takes two arguments and tests whether the first is an instance of the second.  (I guess I didn&#8217;t need to explain that) For example:</p>
<pre><code>function Foo(name)
{
  this.name = name;
}
Foo.prototype.getName = function()
{
  alert(this.name);
}

function FooChild(childName)
{
  Foo.call(this, 'I am a child of Foo and my name is ' + childName);
}
FooChild.prototype = new Foo('');

var fooObject = new Foo('I am foo');
var fooChildObject = new FooChild('Barbar');

alert(fooChildObject instanceof Foo); // true
alert(fooObject instanceof Foo); // true
alert(fooChildObject instanceof FooChild); // true
alert(fooObject instanceof FooChild); // false;</code></pre>
<p>In the above code, it is clear that <code>fooChildObject</code> is an instance of <code>FooChild</code>, and <code>fooObject</code>is an instance of <code>Foo</code>.  However, <code>fooChildObject</code> <strong>is also</strong> an instance of <code>Foo</code>, since its type was inherited from it through the <code>prototype</code> property.  However, <code>fooObject</code> <strong>is not</strong> an instance of <code>FooChild</code> since that type is a child of <code>Foo</code>.</p>
<p>I hope I haven&#8217;t said &#8220;foo&#8221; one too many times for you.</p>
<p>More information about <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Property_Inheritance_Revisited:Determining_Instance_Relationships"><code>instanceof</code> is again available</a> from the excellent Mozilla Developer Center.</p>
<h3>Concluding remarks</h3>
<p>I hope this has helped you to understand the nature of JavaScript&#8217;s built-in inheritance features.  I know I found it very convoluted at first, coming from a class-inheritance background.  I read everything I could find on the subject, and I believe it&#8217;s made me a better JavaScript programmer by understanding some of the &#8220;inner workings&#8221; of the language.  I encourage you to check out some of the references I&#8217;ve provided below.</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://javascript.crockford.com/prototypal.html">Prototypal Inheritance in JavaScript</a> - Douglas Crockford</li>
<li><a href="http://20bits.com/2007/03/08/the-philosophy-of-javascript/">The Philosophy of JavaScript</a> - Jesse of 20bits</li>
<li><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Property_Inheritance_Revisited">Prototype Inheritance Revisited</a> - Mozilla Developer Center</li>
<li><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:The_Employee_Example">The Employee Example</a> - Mozilla Developer Center</li>
</ol>
<hr/>Copyright &copy; 2009 <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/2008/01/24/javascript-and-inheritance/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
