<?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>JavaScript By Example</title>
	<atom:link href="http://www.examplejs.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.examplejs.com</link>
	<description>A few JavaScript tips and tricks I&#039;ve picked up along the way</description>
	<lastBuildDate>Sun, 20 May 2012 14:50:30 +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>Fun with Functions: Declarations vs. Expressions</title>
		<link>http://www.examplejs.com/?p=144</link>
		<comments>http://www.examplejs.com/?p=144#comments</comments>
		<pubDate>Sun, 20 May 2012 04:39:47 +0000</pubDate>
		<dc:creator>Nathaniel</dc:creator>
				<category><![CDATA[Concepts]]></category>
		<category><![CDATA[Core JavaScript]]></category>
		<category><![CDATA[anonymous function expression]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[function declaration]]></category>
		<category><![CDATA[function definition]]></category>
		<category><![CDATA[function expression]]></category>
		<category><![CDATA[global namespace]]></category>
		<category><![CDATA[grouping operator]]></category>
		<category><![CDATA[hoisting]]></category>
		<category><![CDATA[immediately invoked function expression]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[named function expression]]></category>
		<category><![CDATA[scope]]></category>

		<guid isPermaLink="false">http://www.examplejs.com/?p=144</guid>
		<description><![CDATA[There are a few different ways that you can define a function in JavaScript, and their behavior depends entirely on the context in which they&#8217;re defined. The differences in these techniques are subtle, and they can be somewhat confusing at &#8230; <a href="http://www.examplejs.com/?p=144">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>There are a few different ways that you can define a function in JavaScript, and their behavior depends entirely on the context in which they&#8217;re defined. The differences in these techniques are subtle, and they can be somewhat confusing at first.</p>
<p>A <strong>function declaration</strong> is the most common way that JavaScript developers define a function. You&#8217;ve seen it many times before in tutorials, in books and on websites teaching the basics of the language. It looks like this:</p>
<pre>function greet() {
    alert('Hello!');
}</pre>
<p>A function declaration always starts with the <code>function</code> keyword and is always named. According to spec, the following code should throw a syntax error although in reality some browsers accept it as a valid statement:</p>
<pre>function () {
    alert('Hello!');
}</pre>
<p>Conversely, if a JavaScript statement begins with something other than the <code>function</code> keyword, like in the following code sample, then according to the syntactic rules of the language it cannot possibly be a function declaration. In these situations the definition is instead considered a <strong>function expression</strong>.</p>
<pre>var appreciate = function () {
    alert('Thank you!');
};</pre>
<p>The major difference in behavior between function declarations and expressions is that declarations are <a title="ExampleJS.com - Learning JavaScript via Interview Questions Part 2: Hoisting" href="http://www.examplejs.com/?p=127" target="_blank">hoisted</a> to the top of the scope in which they reside while expressions are not.</p>
<p>Another difference is that a function defined as part of a function expression need not be named. We&#8217;re free to provide a name, but this is useless in most situations &#8211; at least in my own personal experience &#8211; because the name is meaningful only to the code within the function definition itself:</p>
<pre>var f1 = function f2() {
    alert(f2);
};

var a = f2; // a is undefined
f1(); // alerts the function definition</pre>
<p>We can also create a function expression by wrapping a function definition within a pair of parentheses. The parentheses are known in JavaScript as the <strong>grouping operator</strong>, and they&#8217;re used to indicate the correct order in which expressions are evaluated. According to the language&#8217;s syntax, they can only contain expressions so the JavaScript parser considers any function definition within parentheses to be function expressions rather than function declarations.</p>
<h2>Immediately invoked function expressions</h2>
<p>If we follow an expression with a pair of parentheses, the JavaScript parser expects that expression to represent a function definition that it can invoke.</p>
<pre>var halve = function (n) {
    return n / 2;
};
halve(8); // returns 4</pre>
<p>Since a function definition wrapped in a pair of parentheses is just one form of a function expression, we can follow it with a pair of parentheses in order to invoke the function immediately after we define it. This is known as an <strong>immediately invoked function expression</strong>.</p>
<p>Immediately invoked function expressions are incredibly useful in <a title="Wikipedia - Unobtrusive JavaScript" href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript#Namespaces" target="_blank">unobtrusive JavaScript</a> programming because they provide a way to create a private scope in which variables and functions are <a title="Matt Kruse's JavaScript Toolbox - JavaScript Best Practices" href="http://www.javascripttoolbox.com/bestpractices/#namespace" target="_blank">kept out of the global namespace</a>. In the following example, we create a library variable that acts as a private namespace in which we can define code that is hidden from</p>
<pre>var box = (function () {
    var contents = [];

    return {
        insert: function (thing) {
            contents.push(thing);
        },
        count: function () {
            return contents.length;
        }
    };
})();

box.insert('abc');
box.insert(123);
box.insert({ width: 640, height: 480 });
box.insert(document.body);
box.insert(function () { alert('Hello!'); });
box.count(); // returns 5
console.log(contents); // throws a reference error since it can't find the 'contents' variable</pre>
<p>Because immediately invoked function expressions accept arguments like any other function we can also use them to essentially save the state of a variable by passing it in.</p>
<pre>var width = 640, height = 480;

var photo = (function (w, h) {
    return {
        getWidth: function () {
            return w;
        },
        getHeight: function () {
            return h;
        }
    };
})(width, height);

width = 1024;
height = 768;

photo.getWidth(); // returns 640
photo.getHeight(); // returns 480</pre>
<p>My earlier <a title="Learning JavaScript via Interview Questions Part 1" href="http://www.examplejs.com/?p=84" target="_blank">article about closures</a> includes another example of using immediately invoked function expressions to save state that you may find enlightening.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.examplejs.com/?feed=rss2&#038;p=144</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning JavaScript via Interview Questions Part 2: Hoisting</title>
		<link>http://www.examplejs.com/?p=127</link>
		<comments>http://www.examplejs.com/?p=127#comments</comments>
		<pubDate>Sat, 19 May 2012 17:30:31 +0000</pubDate>
		<dc:creator>Nathaniel</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Concepts]]></category>
		<category><![CDATA[Core JavaScript]]></category>
		<category><![CDATA[assignment expression]]></category>
		<category><![CDATA[function declaration]]></category>
		<category><![CDATA[function expression]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript function]]></category>
		<category><![CDATA[variable declaration]]></category>

		<guid isPermaLink="false">http://www.examplejs.com/?p=127</guid>
		<description><![CDATA[I&#8217;m surprised by the number of candidates that I&#8217;ve interviewed who apparently believe that a few years of experience writing little more than jQuery calls to manipulate the DOM makes them senior or even mid level JavaScript developers. I certainly &#8230; <a href="http://www.examplejs.com/?p=127">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m surprised by the number of candidates that I&#8217;ve interviewed who apparently believe that a few years of experience writing little more than jQuery calls to manipulate the DOM makes them senior or even mid level JavaScript developers.</p>
<p>I certainly don&#8217;t consider myself an expert at JavaScript &#8211; unless you&#8217;re capable of building something like jQuery or Backbone you cannot call yourself a JavaScript expert, in my humble opinion &#8211; but I feel comfortable stating that if you don&#8217;t understand <a title="A Quick and Easy JavaScript Inheritance Tutorial" href="http://www.examplejs.com/?p=51" target="_blank">how the prototype works</a> (I&#8217;m not talking about the JavaScript library) or what a <a title="Learning JavaScript via Interview Questions Part 1" href="http://www.examplejs.com/?p=84" target="_blank">closure</a> is, then you have no business promoting yourself as a good JavaScript developer.</p>
<p>The following is one of the tests that I occasionally use to see whether a candidate has a solid understanding of one of JavaScript&#8217;s trickier concepts. What text appears in the alert box?</p>
<pre>var width = false,
    height = false;

function init() {
    if (!width || !height) {
        var width = 50;
        height = 25;
    }

    return;

    function height() {}
}

init();
alert(width + ', ' + height);</pre>
<p>It may surprise you to know that this code alerts <code>false, false</code> and not <code>50, 25</code>. It may also surprise you to know that the reason control of the program enters the if block is not because of the false global <code>width</code> and <code>height</code> variables but because of undefined <code>width</code> and <code>height</code> that are <em>local</em> to the <code>init</code> function.</p>
<p>These are the result of a behavior in JavaScript known as <strong>hoisting</strong> in which all variable and function declarations are moved &#8211; &#8220;hoisted&#8221; &#8211; to the top of their scope before the code in that scope is executed.</p>
<p>It might help to see how the JavaScript parser interprets the above code:</p>
<pre>var width, height;

function init() {
    var width;
    function height() {}

    if (!width || !height) {
        width = 50;
        height = 25;
    }

    return;
}

width = false;
height = false;

init();
alert(width + ', ' + height);</pre>
<p>It&#8217;s important to note that the hoisting process moves the declarations to the top of the function rather than the top of the the <code>if</code> block because JavaScript employs <strong>function level scope</strong> rather than the <strong>block level scope</strong> used by languages like C++, Java and Ruby &#8211; the exception to this rule is the <a title="Mozilla Developer Network - let" href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/let" target="_blank"><code>let</code> statement</a> which allows you to declare a block that possesses its own private scope.</p>
<p>Also note that only the variable <em>declaration</em> is hoisted. The assignment expression <code>width = 50</code> remains within the <code>if</code> block so <code>width</code> starts off with a value of <code>undefined</code> which fulfills the <code>!width</code> portion of the conditional test.</p>
<p>I can&#8217;t say personally that I&#8217;ve seen any advantage to this hoisting behavior insofar as variables are concerned, but I find the ability to declare functions at the end of a scope particularly useful from a code organization perspective. I think this comes in handy when there&#8217;s the expectation that other people will read your code &#8211; in my opinion it&#8217;s easier to evaluate the code within a function declaration once you already know the context in which it will be executed.</p>
<p>To avoid confusion with variable hoisting, though, just declare all of your variables in a single statement at the top of your scope like so:</p>
<pre>var name = 'John Smith',
    age = 28,
    city = 'New York City',
    favoriteFoods = [ 'pizza', 'hamburgers', 'spaghetti and meatballs', 'corn on the cob', 'apple pie' ];

    describe();

function describe() {
    var message = 'Hello! My name is ' + name + ', and I' + "'" + 'm ' + age + ' years old! I live in ' + city + '. My favorite foods are: ',
        i, l;

    for (i = 0, l = favoriteFoods.length; i &lt; l; i++) {         if (i &gt; 0) {
        	message += ', ';
        }
        if (i == l - 1) {
        	message += 'and ';
        }
        message += favoriteFoods[i];
    }
    message += '!';
    alert(message);
}</pre>
<p>If I were to declare other functions that contained their own <code>for</code> loops, I could shift the declaration of the <code>i</code> and <code>l</code> variables to the global scope &#8211; in the variable declaration that includes <code>name</code> and <code>age</code> &#8211; although I probably would just declare them within each function to avoid the performance hit that comes with referencing global variables from within a deeper scope.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.examplejs.com/?feed=rss2&#038;p=127</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wading through codec soup: where we are now with HTML5 video</title>
		<link>http://www.examplejs.com/?p=110</link>
		<comments>http://www.examplejs.com/?p=110#comments</comments>
		<pubDate>Sat, 12 May 2012 16:54:32 +0000</pubDate>
		<dc:creator>Nathaniel</dc:creator>
				<category><![CDATA[Concepts]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Industry]]></category>
		<category><![CDATA[aac]]></category>
		<category><![CDATA[codec]]></category>
		<category><![CDATA[format war]]></category>
		<category><![CDATA[h.264]]></category>
		<category><![CDATA[html5 video]]></category>
		<category><![CDATA[mp4]]></category>
		<category><![CDATA[ogg]]></category>
		<category><![CDATA[theora]]></category>
		<category><![CDATA[v8]]></category>
		<category><![CDATA[video format]]></category>
		<category><![CDATA[vorbis]]></category>
		<category><![CDATA[web standards]]></category>
		<category><![CDATA[webm]]></category>

		<guid isPermaLink="false">http://www.examplejs.com/?p=110</guid>
		<description><![CDATA[There was initially some trepidation in pushing HTML5 video due to fragmentation in audio and video format support across the major browsers. The original HTML5 specification required that all browsers support the Theora video and the Vorbis audio codecs &#8211; &#8230; <a href="http://www.examplejs.com/?p=110">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>There was initially some trepidation in pushing HTML5 video due to fragmentation in audio and video format support across the major browsers. The original HTML5 specification required that all browsers support the Theora video and the Vorbis audio codecs &#8211; both <strong>royalty free and unencumbered by any known patents</strong> &#8211; and the Ogg container format, but some companies like Apple opposed this requirement on the grounds that it could be easier for some browsers to support other formats more easily and that HTML historically didn&#8217;t require a specific format for any media content. The risk of an ambush by a previously unknown patent holder undoubtedly also played a part in Apple&#8217;s dissension.</p>
<p>The working group responsible for HTML5 eventually caved on requiring specific format support, revising the specification to merely suggest that browser vendors come to an agreement on a codec for the sake of &#8220;interoperability.&#8221; The result of this was a codec mess with three different formats supported by different sets of browsers:</p>
<ul>
<li>Theora video codec and Vorbis audio codec in an Ogg container natively supported by Firefox, Chrome and Opera.</li>
<li>V8 video codec &#8211; another <strong>royalty free format unencumbered by any known patents</strong> from the same team that developed Theora &#8211; and Vorbis in a Matroska-based WebM container natively supported by Chrome and Opera (Internet Explorer 9 will also play WebM formatted video content if the user has installed a V8 codec).</li>
<li>H.264 video codec &#8211; a format <strong>heavily encumbered by patents</strong> licensed through the MPEG LA group whose membership includes Apple and Microsoft &#8211; and AAC &#8211; Advanced Audio Coding, the same audio format used by Apple&#8217;s touch devices &#8211; in an MP4 container natively supported by all Apple hardware (and thus their Safari browsers), Chrome and Internet Explorer 9.</li>
</ul>
<h2>Google to the rescue?</h2>
<p>A few short months after <a title="Google: Investor Relations - Google Closes On2 Technologies Acquisition" href="http://investor.google.com/releases/2010/0219.html" target="_blank">Google acquired On2</a> Technologies, creators of Theora and the VP8 codec, the company released VP8 as open source as part of their effort to promote an HTML5 video format based on an open format unencumbered by patents. This opened the door for Adobe to announce <a title="Adobe: Flash Platform Blog - Flash Player Will Support VP8" href="http://blogs.adobe.com/flashplatform/2010/05/adobe_support_for_vp8.html" target="_blank">Flash support of the codec</a> and eventually led to Google announcing that they would <a title="The Chromium Blog - HTML Video Codec Support in Chrome" href="http://blog.chromium.org/2011/01/html-video-codec-support-in-chrome.html" target="_blank">drop support of the patent-heavy H.264 codec</a> in order to &#8220;enable open innovation&#8221; and focus on &#8220;completely open codec technologies.&#8221;</p>
<p>This was, of course, great news to the people behind Firefox and Opera who had been working together to promote the open web with their mutual support of the Theora codec, which Google said they would continue to include in Chrome (Opera also supports V8 in Google&#8217;s WebM format).</p>
<p>The only problem was that H.264 was just too entrenched. Apple and Microsoft obviously supported it, being members of the <a title="Wikipedia.org - MPEG LA" href="http://en.wikipedia.org/wiki/MPEG_LA" target="_blank">patent licensing organization</a> behind the codec, as did Adobe&#8217;s Flash player. More importantly, virtually every available piece of computing hardware from desktops and laptops to smart phones and tablets in recent history has had hardware-based H.264 decoding which meant that it was really a no-brainer for content providers to encode their video with the currently &#8220;free&#8221; H.264 codec.</p>
<p>Even in the unlikely event that Google didn&#8217;t realize this going into their announcement, they certainly learned the lesson quickly: as of today Chrome still supports H.264, and support for the codec in Android was never a question. Not even a conversion of all video content on YouTube to the WebM format is going to make much of a difference since there isn&#8217;t any broad hardware support for V8 and Theora (why would there be with the ubiquity of H.264) and content providers are not going to accept the burden of having to encode their video content more than once.</p>
<p>There isn&#8217;t much of an upside from a user or business perspective for unified support of an open standards-based video format on the web, and there&#8217;s a helluva downside for Google if they switched off H.264 support &#8211; the last thing they want is for consumers to experience a failure of YouTube across all smart phones, tablets and interactive televisions.</p>
<p>Google has yet to officially throw in the towel, but Mozilla &#8211; arguably an even stauncher opponent of H.264 than Google &#8211; has seen the writing on the wall. They all but <a title="Mozilla - Video, Mobile, and the Open Web" href="http://hacks.mozilla.org/2012/03/video-mobile-and-the-open-web/" target="_blank">announced that they would somehow integrate H.264 support into future versions of Firefox</a>, stating that it&#8217;s an unfortunate necessity for Mozilla&#8217;s mobile initiatives &#8211; <a title="Mozilla - Firefox for Android" href="http://www.mozilla.org/en-US/mobile/" target="_blank">Firefox on Android</a> and <a title="Mozilla - Boot to Gecko Project" href="http://www.mozilla.org/en-US/b2g/" target="_blank">Boot to Gecko </a>- to succeed and for the organization itself to remain relevant.</p>
<h2>So where does this leave us now?</h2>
<p>Firefox and Opera are the only two major browser clients that do not support H.264. When Mozilla finally releases a version of Firefox that supports the codec, the sole remaining standout of the group will be Opera which as of April 2012 commands a monstrous <a title="StatCounter - Top 5 Browsers on Apr 2012" href="http://gs.statcounter.com/#browser-ww-monthly-201204-201204-bar" target="_blank">1.72% share of the worldwide browser market</a> and <a title="StatCounter - Top 5 Browsers in the United States on Apr 2012" href="http://gs.statcounter.com/#browser-US-monthly-201204-201204-bar" target="_blank">0.63% of the United States market</a>. When that transition occurs there will no longer be any logical reason for anyone whose user base is not made up solely of Opera users to offer web video encoded with Theora or VP8 unless Google defies the popular wisdom and takes the significantly courageous step of removing all H.264 encoded video content from YouTube.</p>
<p>I really don&#8217;t see that happening. I once had the optimistic, and probably misguided, view that a big company like Google could and would take that kind of risk just based on principle. Maybe the old Google that eventually tried to <a title="Wikipedia - Google China: Ending of self-censorship" href="http://en.wikipedia.org/wiki/Google_China#Ending_of_self-censorship" target="_blank">make a stand</a> against the Chinese government&#8217;s censorship policies and dazzled people with their <a title="Mashable - Google Labs Relaunches With Two New Must-See Projects" href="http://mashable.com/2009/04/20/google-labs-makeover/" target="_blank">innovative Google Labs projects</a> would have, but today&#8217;s Google is much more pragmatic and realistic than it has been in the past.</p>
<p>We as web developers can at least take a little bit of comfort in knowing that sooner than later we will no longer have to worry about an inconvenient format war. It&#8217;s not the ideal outcome, but at least it&#8217;s some form of progress that allows us to instead focus all of our energy on creating the coolest possible web applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.examplejs.com/?feed=rss2&#038;p=110</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning JavaScript via Interview Questions Part 1: Closures</title>
		<link>http://www.examplejs.com/?p=84</link>
		<comments>http://www.examplejs.com/?p=84#comments</comments>
		<pubDate>Thu, 19 Apr 2012 19:04:50 +0000</pubDate>
		<dc:creator>Nathaniel</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Concepts]]></category>
		<category><![CDATA[Core JavaScript]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[function declaration]]></category>
		<category><![CDATA[function expression]]></category>
		<category><![CDATA[function level scope]]></category>
		<category><![CDATA[functional scope]]></category>
		<category><![CDATA[immediately invoked function expression]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[variable scope]]></category>

		<guid isPermaLink="false">http://www.examplejs.com/?p=84</guid>
		<description><![CDATA[As the most experienced dedicated JavaScript developer in my company (one of my coworkers could program circles around me but his primary role is to investigate potential technologies to integrate into our platforms) I have the responsibility of conducting code &#8230; <a href="http://www.examplejs.com/?p=84">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As the most experienced dedicated JavaScript developer in my company (one of my coworkers could program circles around me but his primary role is to investigate potential technologies to integrate into our platforms) I have the responsibility of conducting code tests on candidates for front-end developer positions.</p>
<p>There are a few questions I typically use to get an idea of the candidate&#8217;s familiarity with the basics of the language. When I say &#8220;basics&#8221; I don&#8217;t mean whether they know how to declare a variable or find a DOM element by its <em>id</em> attribute, but rather key aspects of the language without intimate knowledge of which one cannot possibly say they are a <strong>good</strong> JavaScript developer.</p>
<p>For example (and I chose this feature because I already covered it in <a title="A Quick and Easy JavaScript Inheritance Tutorial" href="http://www.examplejs.com/?p=51">an earlier post</a>) if you don&#8217;t know what an object&#8217;s <em>prototype</em> is or how JavaScript&#8217;s native inheritance model works then you&#8217;re likely a junior JavaScript developer at best. I don&#8217;t mean to come off as high and mighty, but, really, there&#8217;s a lot more to the language than attaching event handlers.</p>
<p>Speaking of event handlers, let&#8217;s take a look at the following bit of code that illustrates two important aspects of JavaScript that can throw some developers used to more traditional functional programming languages for a loop (I&#8217;ve personally listened to top tier Java developers curse JavaScript over these concepts).</p>
<pre>function initButtons() {
    var body = document.getElementsByTagName("body")[0],
        button;
    for (var i = 0; i &lt; 5; i++) {
        button = document.createElement('button');
        button.addEventListener('click', function (e) {
            alert(i);
        });
        button.appendChild(document.createTextNode('Button ' + i));
        body.appendChild(button);
    }
}</pre>
<p>So what happens when we click the buttons generated by the execution of <code>initButtons</code>?</p>
<p>Without fail every candidate I asked this question to responded that we would see an alert box with the number of the button we clicked, and as you can probably guess that isn&#8217;t the correct answer since it&#8217;s the &#8220;obvious&#8221; one (and if the answer were really that obvious there wouldn&#8217;t be much point to the question).</p>
<p>However, we actually see an alert box with the number 6 no matter which button we click. The reason this happens is because when <code>addEventListener</code> is invoked on button through each iteration of the for loop during the execution of <code>initButtons</code> an entity known as a <strong>closure</strong> is created.</p>
<p>A closure is, from a simplified perspective, a function that is executed in a scope other than the one in which it was defined while still retaining references to variables that were in its original scope.</p>
<p>When we invoke <code>initButtons</code>, the <code>for</code> loop defines an anonymous function that alerts the value of <code>i</code>. In many programming languages this would mean that the function can only be executed within the scope of <code>initButtons</code>, but JavaScript supports first-class functions meaning that functions are just objects and thus can be passed around. In this case each anonymous function is passed into a <code>button</code>&#8216;s <code>addEventListener</code> method as an argument which assigns it to be executed in a different scope at a later time. The creation of the closure means that even though the scope of this invocation of <code>initButtons</code> has expired by the time the function actually gets executed the function can still access in-scope variables &#8211; for instance, the variable <code>i</code>.</p>
<p>So if the event handling function remembers <code>i</code> when it gets called by a click of the button it&#8217;s assigned to, shouldn&#8217;t the alert box have the appropriate value of <code>i</code>?</p>
<p>Well, no, and the reason for this is because JavaScript has <strong>function level scope</strong>. Armed with this little tidbit of information it should now be easier to figure out what&#8217;s going on.</p>
<p>When the <code>for</code> loop runs, the variable declaration of <code>i</code> occurs <strong>once</strong> within the scope of <code>initButtons</code> even though it may appear that the variable is being defined during each iteration. Each of those five anonymous functions passed to the <code>addEventListener</code> method is thus <strong>referencing the same exact variable</strong> <code>i</code> which by the time <code>initButtons</code> is done has the value 5.</p>
<p>So how do we resolve this issue?</p>
<p>The answers I often hear involve using the current value of <code>i</code> in the value of the <code>id</code> or <code>class</code> attribute or inserting it into <code>button's</code> label &#8211; essentially some variation of modifying the DOM to &#8220;remember&#8221; the value.</p>
<p>While these techniques will certainly work, <strong>they introduce unnecessary complexity into the code</strong> &#8211; why crawl the DOM and parse attributes if you don&#8217;t need to? &#8211; and more importantly miss the whole point of the question which is to understand how JavaScript handles closures and scope.</p>
<p>To that end let&#8217;s take a look at a slightly modified version of the above code:</p>
<pre>for (var i = 0; i &lt; 5; i++) {
    button = document.createElement('button');
    button.addEventListener( 'click', (function (i) {
        return function (e) {
            alert(i);
        };
    })(i) );
    button.appendChild(document.createTextNode('Button ' + i));
    body.appendChild(button);
}</pre>
<p>The big difference here is that we have replaced the simple function object passed into the <code>addEventListener</code> method with an <strong>immediately invoked anonymous function expression</strong> &#8211; essentially a function that is executed as soon as it&#8217;s defined.</p>
<p>This new function accepts some value as a local variable <code>i</code> &#8211; a new local variable is implicitly defined for each parameter we include in a function declaration &#8211; and returns an anonymous function that alerts that value when executed: the variable <code>i</code> in <em>this</em> <code>alert</code> statement refers to the parameter <code>i</code> and not the <code>i</code> created as a variable local to <code>initButtons</code> when the <code>for</code> loop runs.</p>
<p>The outer anonymous function &#8211; the one that accepts the parameter <code>i</code> &#8211; is wrapped in parentheses to identify it as a <strong>function expression</strong> &#8211; an entity that can actually be executed as opposed to a <strong>function declaration</strong> which can only define the function as a variable within its parent scope. Thus, in the modified code snippet that outer function is immediately invoked with the current value of <code>i</code>, and the returned function which recognizes <em>that</em> <code>i</code> is passed to the <code>addEventListener</code> method.</p>
<p>The final version of <code>initButtons</code> is as follows:</p>
<pre>function initButtons() {
    var body = document.getElementsByTagName("body")[0],
        button;
    for (var i = 0; i &lt; 5; i++) {
        button = document.createElement('button');
        button.addEventListener( 'click', (function (i) {
            return function (e) {
                alert(i);
            };
        })(i) );
        button.appendChild(document.createTextNode('Button ' + i));
        body.appendChild(button);
    }
}</pre>
<p>It may be helpful in understanding what&#8217;s going on to see <code>initButtons</code> rewritten in the following way:</p>
<pre>function initButtons() {
    var body = document.getElementsByTagName("body")[0],
        button,
        callbackGenerator = function (i) {
            return function (e) {
                alert(i);
            };
        };
    for (var i = 0; i &lt; 5; i++) {
        button = document.createElement('button');
        button.addEventListener( 'click', callbackGenerator(i) );
        button.appendChild(document.createTextNode('Button ' + i));
        body.appendChild(button);
    }
}</pre>
<p>Now the buttons act the way we expect them to by alerting the number that corresponds to their label.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.examplejs.com/?feed=rss2&#038;p=84</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A JavaScript &#8220;Database&#8221; Using LocalStorage Part 1</title>
		<link>http://www.examplejs.com/?p=66</link>
		<comments>http://www.examplejs.com/?p=66#comments</comments>
		<pubDate>Mon, 16 Apr 2012 18:02:14 +0000</pubDate>
		<dc:creator>Nathaniel</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Web App Development]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Local Storage]]></category>
		<category><![CDATA[localStorage]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[web storage]]></category>

		<guid isPermaLink="false">http://www.examplejs.com/?p=66</guid>
		<description><![CDATA[The W3C Web Storage specification describes a standardized API through which web browsers can support persistent client side data storage. This improves on the rather archaic cookie mechanism in several ways: Storage size: Cookies max out at around 4KB per domain &#8230; <a href="http://www.examplejs.com/?p=66">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The <a title="W3C Web Storage specification" href="http://dev.w3.org/html5/webstorage/" target="_blank">W3C Web Storage specification</a> describes a standardized API through which web browsers can support persistent client side data storage. This improves on the rather archaic <strong>cookie</strong> mechanism in several ways:</p>
<ul>
<li>Storage size: Cookies max out at around 4KB per domain whereas web storage offers up to 5MB of space in Firefox, Chrome, Safari and Opera and 10MB in Internet Explorer</li>
<li>Multiple transactions: Complicated management code is necessary to handle more than one transaction on the same site with cookies</li>
<li>Structure: Web storage provides a better programmatic interface in the form of an associative array model of key-value pairs allowing for more complex data structure and a closer mapping to the popular JSON data format</li>
<li>Client side only: Local storage doesn&#8217;t get transferred to the server with each HTTP request on the domain</li>
<li>Security: Cookies are vulnerable to exploits such as cross site scripting whereas web storage objects can only access data stored on the same domain</li>
</ul>
<p>Web Storage comes in two flavors: Session Storage and Local Storage. Session Storage keeps track of all data for a particular page in a particular browser session which can be useful as a failsafe against accidental page reloads or as a mechanism for storing user progress through a single-page web app.</p>
<p>However, I find the Local Storage feature to be much more interesting and useful as it is accessible by <strong>any page in a domain</strong> and persists through a theoretically infinite number of browser sessions essentially laying the foundation for a client-side database of sorts.</p>
<p>From a JavaScript perspective Local Storage is just another object, not surprisingly named <code>localStorage</code>, with a number of useful and straightforward methods:</p>
<ul>
<li><code>getItem</code> &#8211; Retrieve the value of the specified key.</li>
<li><code>setItem</code> &#8211; Set the value of the specified key.</li>
<li><code>removeItem</code> &#8211; Remove the entry at the specified key.</li>
<li><code>clear</code> &#8211; Remove all entries from <code>localStorage</code>.</li>
<li><code>length</code> &#8211; Retrieve the number of entries in <code>localStorage</code>.</li>
<li><code>key</code> &#8211; Get the key at the specified index in <code>localStorage</code>.</li>
</ul>
<p>These are useful for dealing with small amounts of data organized in relatively simple structures, but if we want to interact with larger volumes of data in a more database-like construct we have to roll our own methods to manipulate <code>localStorage</code>.</p>
<h2>Creating the database class</h2>
<p>The first thing we need to do is create the database class. This will be a global object that can be instantiated so we want to wrap it in a closure that keeps a local reference to the original <code>window</code> object &#8211; we do this with an immediately invoked anonymous function expression that includes <code>window</code> as a parameter:</p>
<pre>(function ( window, undefined ) {
    var Database = function () {};
}(window);</pre>
<p>Each instance of this class will represent a single database within <code>localStorage</code> so the constructor should accept a database name as an argument &#8211; this name will be the key for the database in the <code>localStorage</code> object.</p>
<p>The first thing the constructor needs to do is create a local object that will represent the database and initialize it with the data in <code>localStorage</code>. <code>localStorage</code> stores JSON representations of its data so we need to use <code>JSON.parse</code> in order to end up with an actual object, but we invoke this only after we&#8217;ve checked that the database already exists in <code>localStorage</code> &#8211; why bother wasting resources on a <code>parse</code> call when there&#8217;s nothing to parse?</p>
<p>We accomplish this by using the short-circuit behavior of the <code>&amp;&amp;</code> conditional in which the expression on the right only gets executed if the expression on the left evaluates to <code>true</code>. We also throw in some code to assign an empty object to <code>database</code> if it turns out that the database doesn&#8217;t exist in <code>localStorage</code>.</p>
<pre>var Database = function (databaseName) {
    var database = localStorage[databaseName];
    if (!(database &amp;&amp; (database = JSON.parse(database)))) {
        database = {};
    }
};</pre>
<p>Now we have a database object has been initialized to either the object representation of the JSON from <code>localStorage</code> or an empty object literal. In the latter case we need to take one more step which is to save this new, empty database object to <code>localStorage</code>. In fact saving the current contents of a database object is a necessary piece of functionality that the API should expose so it behooves us to implement a <code>commit</code> method.</p>
<p>Committing data to <code>localStorage</code> is essentially the opposite of retrieving data from <code>localStorage</code> so we need to first serialize the database object (<strong>serialization</strong> is the process of converting a data structure into a simpler format that can more easily be stored or transmitted) using the <code>JSON.stringify</code> method, and since serialization sounds to me like something that we might be interested in doing with the database object outside of the context of a commit action we should probably separate it into its own method:</p>
<pre>this.serialize = function () {
    return JSON.stringify(database);
};

this.commit = function () {
    localStorage[databaseName] = this.serialize();
};</pre>
<p>Now that we have the very basic backbone of a database object in place we can focus on inserting and manipulating data which we&#8217;ll discuss in the next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.examplejs.com/?feed=rss2&#038;p=66</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Quick and Easy JavaScript Inheritance Tutorial</title>
		<link>http://www.examplejs.com/?p=51</link>
		<comments>http://www.examplejs.com/?p=51#comments</comments>
		<pubDate>Mon, 13 Feb 2012 04:56:07 +0000</pubDate>
		<dc:creator>Nathaniel</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Concepts]]></category>
		<category><![CDATA[Prototypes]]></category>
		<category><![CDATA[classical inheritance]]></category>
		<category><![CDATA[constructor]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JavaScript prototype]]></category>
		<category><![CDATA[JavaScript best practices]]></category>
		<category><![CDATA[JavaScript objects]]></category>
		<category><![CDATA[object literal]]></category>
		<category><![CDATA[Object object]]></category>
		<category><![CDATA[object oriented programming]]></category>
		<category><![CDATA[prototypal inheritance]]></category>
		<category><![CDATA[prototype chain]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[__proto__]]></category>

		<guid isPermaLink="false">http://www.examplejs.com/?p=51</guid>
		<description><![CDATA[JavaScript is not a class-based object oriented programming language and thus has no concept of a class, unlike languages like C++ and Java that use classical inheritance. Rather it uses prototypal inheritance - every object inherits from some other object through a concept known &#8230; <a href="http://www.examplejs.com/?p=51">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>JavaScript is not a class-based object oriented programming language and thus has no concept of a <strong>class</strong>, unlike languages like C++ and Java that use classical inheritance. Rather it uses <strong>prototypal inheritance</strong> - every object inherits from some other object through a concept known as the <strong>prototype chain</strong>.</p>
<h2>Everything is an object</h2>
<p>Well, not <em>everything</em>.</p>
<p><strong>Operators</strong> like <code>+</code> and <code>%</code> aren&#8217;t objects.</p>
<p>A <strong>literal</strong> such as <code>"Howdy"</code> isn&#8217;t technically an object, but if a variable <code>str</code> that is assigned the value <code>"Howdy"</code> calls one of the <code>String</code> object&#8217;s methods &#8211; e.g. <code>charAt</code> - then <code>str</code> is temporarily converted to an instance of <code>String</code> for as long as it takes to execute the function code.</p>
<p>The same goes for numbers like <code>123</code> and arrays like <code>[ "a", "b", "c" ]</code>.</p>
<p>Any function inherits from the <code>Function</code> object which itself inherits from the <code>Object</code> object. In fact, <code>Object</code> is essentially the mother of all objects since most everything either inherits from <code>Object</code> directly or inherits from <code>String</code>, <code>Number</code>, <code>Array</code>, <code>Boolean</code>, or any of the other &#8220;base&#8221; objects (<code>Date</code>, <code>Math</code>, <code>RegExp</code>, and <code>Global</code> are in there, too) which themselves all inherit from <code>Object</code> in one glorious circle of life.</p>
<h2>Creating objects</h2>
<p>There are two ways to create new objects in JavaScript. The first is to define an <strong>object literal</strong> which is a collection of name-value pairs separated by commas and encased in curly braces.</p>
<pre>var pet = {
    name: "Fido",
    species: "dog",
    bark: function () {
        alert("WOOF!");
    }
};</pre>
<p>These don&#8217;t have an explicit <code>prototype</code> property, but inherit &#8220;under the hood&#8221; from <code>Object's</code> prototype (Webkit and Mozilla browsers allow you to view an <strong>object literal&#8217;s</strong> prototype via the <code>__proto__</code> property which is unavailable in Internet Explorer).</p>
<p>The other way to create an object is to define a <strong>constructor</strong> function that when invoked creates an object.</p>
<pre>var Person = function (name) {
    this.name = name;
};
var me = new Person("Nathaniel");</pre>
<p>The variable <code>me</code> is assigned an object with only one property - <code>name</code> has the value <code>"Nathaniel"</code> - plus an &#8220;under the hood&#8221; reference to a prototype object which stores a reference to the constructor as well as a pointer to <code>Object's</code> prototype from which it inherits. As alluded to above the &#8220;under the hood&#8221; prototype reference is exposed in Webkit and Mozilla browsers as <code>__proto__</code>.</p>
<h2>Prototypes</h2>
<p>So what happens when you modify <code>Person's</code> prototype?</p>
<pre>var Person = function (name) {
    this.name = name;
};
Person.prototype.greet = function () {
    alert("Hello! My name is " + this.name + ".");
};
var me = new Person("Nathaniel");</pre>
<p><code>me</code> itself remains the same with just the one <code>name</code> property, but <code>__proto__</code> now contains a method <code>greet</code>. Properties and methods defined on a constructor&#8217;s prototype are available to all instances by reference, and don&#8217;t contribute to instantiation overhead.</p>
<p>And since the <code>greet</code> method is part of the prototype, which is associated to instances <strong>by reference</strong>, every instance of <code>Person</code> points to the same definition which itself references the <code>name</code> property of the specific instance.</p>
<pre>var you = new Person("Joe Sixpack");
var her = new Person("Jennifer");

me.greet(); // Alerts "Hello! My name is Nathaniel."
you.greet(); // Alerts "Hello! My name is Joe Sixpack."
her.greet(); // Alerts "Hello! My name is Jennifer."</pre>
<p>That&#8217;s all obvious, but it&#8217;s important to note that you can also do the following:</p>
<pre>Person.prototype.greet = function () {
    alert("Howdy, neighbor!");
};

me.greet(); // Alerts "Howdy, neighbor!"
you.greet(); // Alerts "Howdy, neighbor!"
her.greet(); // Alerts "Howdy, neighbor!"</pre>
<p>If you change the value of any member of a constructor&#8217;s prototype <strong>all</strong> instances both existing and future recognize the change, effective immediately.</p>
<h2>Setting up inheritance between two objects</h2>
<p>Let&#8217;s say we want to create a new &#8220;class&#8221; object <code>Employee</code> that inherits from <code>Person</code> but has its own specialized properties or methods. First things first, let&#8217;s create the <code>Employee</code> constructor:</p>
<pre>var Employee = function (name, company, title) {
    this.name = name;
    this.company = company;
    this.title = title;
};</pre>
<p>In order to set up inheritance between <code>Employee</code> and <code>Person</code> we need to assign <code>Person</code> as the prototype of <code>Employee</code>. There are two ways to do this.</p>
<pre>Employee.prototype = new Person();
Employee.prototype.constructor = Employee;</pre>
<p>The first line of code establishes that <code>Employee's</code> prototype should essentially be an instance of <code>Person</code> and thus have access to all of <code>Person's</code> prototype members just as any instance would. JavaScript by default assigns <code>Person</code> to the <code>constructor</code> property of <code>Employee's</code> prototype, however, so the second line is needed to reset <code>Employee's</code> constructor to <code>Employee</code>.</p>
<p>There&#8217;s a slight problem here, though, that isn&#8217;t evident in our specific example involving <code>Person</code>. <code>Person's</code> constructor is a function like any other function capable of running whatever code we feel like including. For example, let&#8217;s say <code>Person's</code> constructor looked like this instead of the above example:</p>
<pre>var Person = function (name) {
    this.name = name;
    $("body").append('&lt;p&gt;New person added: ' + this.name);
};</pre>
<p>This probably isn&#8217;t a realistic example, but the point is that the constructor function can run any code including other functions that we may not want to execute if we&#8217;re not creating a straight up instance of <code>Person</code>. We want to be able to grab <code>Person's</code> prototype without actually invoking its constructor. To do this we use a second similar technique.</p>
<pre>var proxy = function () {};
proxy.prototype = Person.prototype;
Employee.prototype = new proxy();
Employee.prototype.constructor = Employee;</pre>
<p>Since we don&#8217;t want to invoke <code>Person's</code> constructor we instead use a dummy function as a replacement constructor to instantiate as <code>Employee's</code> prototype. The end result is the same since <code>Employee</code> doesn&#8217;t care about anything in <code>Person's</code> constructor &#8211; it only wants to know what it should inherit through the prototype.</p>
<p>We still need to reset the <code>constructor</code> property of <code>Employee's</code> prototype which points to <code>Person</code> since it&#8217;s inherited from <code>Person</code>.</p>
<p>In either case we end up with an <code>Employee</code> object whose instances have a different set of constructed properties than instances of <code>Person</code> but have access to the <code>greet</code> method from <code>Person's</code> prototype.</p>
<p>Keep in mind, though, that said access to <code>greet</code> is still association by reference so if you change the value of <code>greet</code> in <code>Person's</code> prototype than any instance of <code>Employee</code> will reflect that change going forward.</p>
<h2>The prototype chain</h2>
<p>As objects inherit from one another they form what is popularly described as a <strong>prototype chain</strong> along which the JavaScript engine can search for a called property or method.</p>
<pre>var e = new Employee("Steve Jobs", "Apple", "CEO");
alert(e.toString()); // Alerts "[object Object]"</pre>
<p>When we invoke <code>e.toString</code> JavaScript first looks at the instance itself to see if it has a property or method of that name. Not finding such a member, JavaScript then looks at the instance&#8217;s prototype, which refers to <code>Person's</code> prototype, to see if there&#8217;s a <code>toString</code> property or method defined there. Since <code>Person's</code> prototype doesn&#8217;t include <code>toString</code>, JavaScript then has to go up the prototype chain to the next link, which happens to be the <code>Object</code> object. That prototype <em>does</em> contain a <code>toString</code> method which gets invoked and alerts the string representation of the object.</p>
<p>Only after JavaScript fails to find the property or method in question anywhere on the prototype chain does it give the <code>undefined</code> notification.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.examplejs.com/?feed=rss2&#038;p=51</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Use Prototypes&#8230; and I Don&#8217;t Mean the Framework</title>
		<link>http://www.examplejs.com/?p=45</link>
		<comments>http://www.examplejs.com/?p=45#comments</comments>
		<pubDate>Mon, 13 Feb 2012 04:31:09 +0000</pubDate>
		<dc:creator>Nathaniel</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Concepts]]></category>
		<category><![CDATA[Prototypes]]></category>
		<category><![CDATA[classical inheritance]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JavaScript prototype]]></category>
		<category><![CDATA[JavaScript best practices]]></category>
		<category><![CDATA[prototypal inheritance]]></category>

		<guid isPermaLink="false">http://www.examplejs.com/?p=45</guid>
		<description><![CDATA[I&#8217;m quite surprised at the number of developers I&#8217;ve worked with who have a working knowledge of JavaScript but don&#8217;t know how JavaScript prototypes work. Of all the accomplished software engineers I&#8217;ve had the privilege of working with only two had even &#8230; <a href="http://www.examplejs.com/?p=45">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m quite surprised at the number of developers I&#8217;ve worked with who have a working knowledge of JavaScript but don&#8217;t know how JavaScript prototypes work.</p>
<p>Of all the accomplished software engineers I&#8217;ve had the privilege of working with only two had even heard of the concept, and one of those guys is pretty close to brilliant having done crazy things like implementing <a title="Wikipedia: Self (programming language)" href="http://en.wikipedia.org/wiki/Self_(programming_language)" target="_blank">Self</a> in JavaScript!</p>
<p>About a month after I started working at my current place of employment, I was assigned the task of developing a new version of one of our widgets which included a number of &#8220;panels&#8221; that users would interact with to accomplish their goal. Different panels could have different types of functionality so an obvious starting point was to create a basic &#8220;Panel&#8221; object from which other types of panels would inherit, and this in fact was one of the project requirements provided to me by the engineering manager.</p>
<p>During the first code review involving yours truly and that manager, it became very clear within moments that he had absolutely no idea what JavaScript prototypes were and had never seen JavaScript&#8217;s native inheritance in action. His only experience with &#8220;prototype&#8221; in the context of JavaScript was with the <a title="Prototype JavaScript framework" href="http://www.prototypejs.org/" target="_blank">Prototype framework</a> he used for client-side coding.</p>
<p>This is a software engineer who, while spending most of his time on the server side working with languages like Ruby that use the classical inheritance paradigm, was solely responsible for all of the JavaScript programming for the application with the most complex user interactions!</p>
<p>I tried to explain how prototypal inheritance worked in JavaScript, but I might as well have been speaking a foreign language &#8211; he just couldn&#8217;t wrap his head around the concept (granted, this was during the span of the one hour during which the code review session took place).</p>
<p>His first reaction was to ask me to consider implementing a more classical inheritance approach in JavaScript in case he or other engineers on the team had to work with my code. This would have sparked a brief debate on the merits of emulating classical inheritance when a perfectly good native inheritance scheme is available, but he was called into an emergency meeting and the subject never came up again since I took over pretty much all major JavaScript development for the company.</p>
<p>While I can understand where my manager was coming from I really didn&#8217;t see much point in reinventing the wheel. JavaScript tackles the issue of object inheritance in a clean and easy way with its prototype paradigm, and while a number of JavaScript gurus such as <a title="Douglas Crockford: Classical Inheritance in JavaScript" href="http://www.crockford.com/javascript/inheritance.html" target="_blank">Douglas Crockford</a>, <a title="John Resig: Simple JavaScript Inheritance" href="http://ejohn.org/blog/simple-javascript-inheritance/" target="_blank">John Resig</a> and <a title="Dean Edwards: A Base Class for JavaScript Inheritance" href="http://dean.edwards.name/weblog/2006/03/base/" target="_blank">Dean Edwards</a> have served up their own solutions as to how to emulate the classical inheritance methodology as seen in Java, C++ and other class-based languages, any one of them will likely tell you that in most scenarios prototypical inheritance is the way to go in JavaScript: you won’t have to invest resources in writing the emulators and any new JavaScript programmer added to the team can hit the ground running with the functionality inherent to the language.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.examplejs.com/?feed=rss2&#038;p=45</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

