19 April 2011

Understanding JavaScript Inheritance

JavaScript is a language which can be difficult to understand deeply. As opposed to most object-oriented programming languages, JavaScript is not class-based, it is prototype-based. This means that objects inherit from other objects, not classes. But while it is prototype-based, it has a syntax and features to make it seem like it is class-based. Because JavaScript seems confused about whether it is class-based or prototype-based, it can be difficult to use it correctly in either way. However, with a little bit of information about how JavaScript works behind the scenes, it is possible to emulate class-based inheritance or take full advantage of prototype-based inheritance.

My goal in this blog post is to try to get to the root of how JavaScript inheritance works in three cases: without explicitly doing it, using modern prototype-based inheritance, and using modern pseudo-class-based inheritance.

(This post is definitely not for beginners to JavaScript, but for someone who already knows it and wants to understand it a little deeper.)

Functions

function Animal() { }

On the surface, this code seems to create a function called Animal. But with JavaScript, the full truth is slightly more complicated. What actually happens when this code executes is that two objects are created. The first object, called Animal, is the constructor function itself. The second object, called Animal.prototype, has a property called Animal.prototype.constructor, which points to Animal. Animal has a property which points back to its prototype, Animal.prototype. This is illustrated in this diagram:


Although not shown in the diagram above, Animal.prototype actually inherits from the Object.prototype object. All objects in Javascript ultimately inherit from the Object.prototype object. A link from the object to the object it inherits from is stored in the internal __proto__ property (which is not publicly available in all browsers). The __proto__ property is illustrated in this diagram with a dashed line:



The "new" Operator

function Planet() { }
var earth = new Planet();

JavaScript's built-in "new" operator is how JavaScript attempts to emulate class-based inheritance. The "new" operator creates a new object, in this case called "earth", calls the function "Planet" on it, then sets the __proto__ property of the new object to Planet.prototype.



This allows functions to act like classes in some ways, but creating a deep inheritance hierarchy is impossible using just the "new" operator. For example, how could you create a new class that inherits from the Planet "class"?

Using the "Object.create" Function to Implement Prototype-Based Inheritance

Because of the fact that most browsers do not let programmers directly access the __proto__ property, it is difficult to create objects in JavaScript that directly inherit from another object--the very definition of prototype-basd inheritance. To simplify this, Douglas Crockford discovered an improved way to create new objects in JavaScript. His function, illustrated below, creates an object which inherits from the object passed to the function, thus providing a simple method of implementing prototypal inheritance.

function createObject(parent) {
  function TempClass() {}
  TempClass.prototype = parent;
  var child = new TempClass();
  return child;
}

I will walk through what this function does one line at a time with diagrams.

1. function TempClass() {}



2. TempClass.prototype = parent



3. var child = new TempClass()



A version of this function is actually implemented on all the newer browsers (including Internet Explorer 9, Firefox 4, and Chrome 9) as "Object.create". But it is easy to implement it yourself if you need to support older browsers, using the formulation above or that described by Douglas Crockford in Prototypal Inheritance in JavaScript.

Using the Inherit Function to Emulate Class-Based Inheritance

Imagine that you wanted to use class-based inheritance in JavaScript. You might want to do something like this:

function Mammal() {
  this.hasHair = true;
}

function Bear() {
  Mammal.call(this); // Call parent constructor
  this.roars = true;
}
inherit(Bear, Mammal);

var yogi = new Bear();
alert(yogi.hasHair); // This should display 'true'

Note the call to "Mammal.call" in the Bear constructor. This calls the parent constructor, similar to super() in Java or base() in C#. To implement the above, you can create some version of the "inherit" function:

function inherit(sub, super) {
  var newSubPrototype = createObject(super.prototype); 
  newSubPrototype.constructor = sub; 
  sub.prototype = newSubPrototype;
}

The inherit function takes two classes (functions) as parameters, and makes the first class inherit from the second one. In memory, here is how each line of the inherit function works...

1. Before the function is run, we have two classes, sub and super:



2. var newSubPrototype = createObject(super.prototype)



3. newSubPrototype.constructor = sub



4. sub.prototype = newSubPrototype



Using one of these two methods can allow you to implement whichever inheritance scheme you like, which is one of the reasons why JavaScript can be so powerful if understood correctly.

Related Links
  1. Tim Caswell's Learning Javascript with Object Graphs, Part 2, and Part 3
  2. Dmitry A. Soshnikov's JavaScript. The core.
    (A deep understanding of scope, inheritance, closures.)
  3. Mozilla's JavaScript Reference
  4. Douglas Crockford's Prototypal Inheritance in JavaScript
(Updated 2011-04-23 - Additional clarifications based on comments.)
(Updated 2011-05-16 - Added missing call to super constructor in Bear constructor.)

04 April 2011

Installing Google's Closure Linter on Windows

I am working on a JavaScript project right now, so I decided to try out Closure Linter, Google's relatively new JavaScript code style verification tool that is part of their Closure Tools collection. I'm using Windows 7 64-bit, and their instructions for using Closure Linter on Windows do not quite make it clear what all needs to be done to get it working.

In case this is helpful to someone else in the future, here are the steps I took (modified from those found at How to Use Closure Linter):
  • Download and install Python 2.7.x for Windows 32-bit. Note that you must choose the 32-bit version of Python from the 2.7.x branch to ensure that you can use the EasyInstaller program needed for the next step.
  • Download and install SetupTools/EasyInstall for Python 2.7.
  • Install Closure Linter:
    • In a command prompt, change directory to to C:\Python27\Scripts
    • Run this command:
      easy_install http://closure-linter.googlecode.com/files/closure_linter-latest.tar.gz
Now you will be able to run Closure Linter using variations on this command:
C:\Python27\Scripts\gjslint --nojsdoc -r DIRECTORY_TO_LINT

Good luck with the tool!

06 January 2011

Visual Studio Color Themes

Whenever I get tired of my color scheme in Visual Studio, I go to Studio Styles and try out a new theme. After that, I switch my font to a more readable font, like Deja Vu Sans Mono.

19 November 2010

SAML 2.0

I have been working a lot with SAML recently, which is a protocol for standardizing single sign on (SSO) between sites. A good number of sites and products use SAML as a SSO protocol, including Google Apps and Moodle, important sites to communicate with in my particular case.

I'm working in .NET 3.5, which unfortunately has no built-in support for SAML 2.0, but there are many third-party libraries and references to build your own support for it.

Here are some of the best links I have found for learning SAML.

References
Examples

20 October 2010

Importing GWT SDK Samples into Eclipse

I've recently started working with the Google Web Toolkit (GWT), which seems pretty sweet from everything I've read so far. It has great integration with an IDE, in this case Eclipse, which is absolutely essential.

Unfortunately, it was hard to find a way to easily open GWT's sample projects in Eclipse, but after a little trial and error, here is what I came up with. For each sample project you want to use, do the following:
  1. Create a new Java project with the name of the sample project you want to use, for example, "Hello". Use all the other default settings, and press "Finish".
  2. Right-click on the project and choose "Import". Choose "General" -> "File System", then press "Next".
  3. Browse to the directory of the sample project you want to import. On my computer, the project was found at something like: C:\Program Files\eclipse\plugins\com.google.gwt.eclipse.sdkbundle...\gwt-2.0.4\samples. Select all, then press "Finish".
  4. Right-click on the project and choose "Google" -> "Web Toolkit Settings". Check the "Use Google Web Toolkit" check box.
  5. Go the the "Java Build Path" section of the project's properties. Change the default output folder to something like: "/Hello/war/WEB-INF/classes" (This will be different depending on your project name).
That's all! Good luck and have fun trying out GWT's samples.

12 November 2009

Best Android Apps by Category

Social Networking
  • Twidroid (Twitter client)
  • Facebook
Podcasts
  • DoggCatcher
    • Easy control over when podcasts downloaded
Desktop Music Syncing Software
Music Listening
  • Built-in Music App
Language Learning
  • Anki
    • Flashcard app
    • Does not sync with Anki Online
Productivity
  • Remember the Milk (Todo list w/ online sync)
  • Movies by Flixster
  • FeedR News Reader
Utilities
  • WiFi OnOff
  • Barcode Scanner
  • Astro (File Browser)

03 February 2009

Creating a Clojure GUI Application with SWT

In my explorations of Clojure, I have been developing a desktop GUI application that uses SWT, the graphics toolkit that Eclipse uses. Once you get going, SWT is fairly intuitive to program in with Clojure, but you might need a little help to get started. Here is an example of a barebones app in SWT:
(ns swttest
(:import (org.eclipse.swt.widgets Display Shell)
(org.eclipse.swt.layout GridLayout)
(org.eclipse.swt.events ShellAdapter)))

(defn create-shell [display shell]
(let [layout (GridLayout.)]
(doto shell
(.setText "SWT Test")
(.setLayout layout)
(.addShellListener
(proxy [ShellAdapter] []
(shellClosed [evt]
(System/exit 0)))))))

(defn swt-loop [display shell]
(loop []
(if (.isDisposed shell)
(.dispose display)
(do
(if (not (.readAndDispatch display))
(.sleep display))
(recur)))))

(defn begin []
(let [display (Display.)
shell (Shell. display)]
(create-shell display shell)
(.setSize shell 700 700)
(.open shell)
(swt-loop display shell)))

(begin)
On Mac, you will need to add the "-XstartOnFirstThread" command line option or your application will crash soon after launching.

Update:
I originally left out the line "(create-shell display shell)". The code above is now corrected.

See also:

20 January 2009

Google Code and Subversion

I recently started using Google Code for hosting a new open source project I'm working on (written in Clojure) in my spare time. Google Code uses Subversion for version control, which some predict is going to change soon to Git. While I am pretty familiar with the command line options for the Git version control system, I'm definitely not with Subversion. Maybe Google Code will switch to Git soon, but until it does, I needed to use Subversion, so I went looking for some GUI-based Subversion clients to simplify its use.

Windows

Finding a good Windows client was easy. TortoiseSVN is an Explorer shell extension that is free, stable, and complete. It worked right out of the box with Google Code and I didn't have to read a single line of documentation to become proficient at it.

Mac

The situation wasn't quite as simple for Mac. There are multiple non-free clients for Mac, but I wanted to stick with open source if possible. The closest thing to TortoiseSVN for Mac is something called SCPlugin, but it is incomplete and development on it seems to have stalled in 2005 or 2006.

SvnX is the one I ended up choosing. It is not quite as intuitive as TortoiseSVN, but it seems to get the job done. To get it working with Google Code, I had to run this command on the command line in order to accept the security certificate:
svn list https://GOOGLE_CODE_CHECKOUT_URL
That's it! Off to do some programming.

22 December 2008

My Favorite Mouse

As a programmer, I naturally spend a good portion of my waking hours--if not the majority--in front of a computer. This didn't seem a problem for the first quarter century of my life, but then about three years ago, I started experiencing pain in my mousing wrist. My first thought was that the beginning of carpal tunnel syndrome was setting in, which freaked me out.

I immediately set out to try more ergonomic input devices, and I switched to a pen input device at home and a radical ergonomic mouse at work. While the pen input device worked fairly well, the ergonomic mouse I chose proved to be the single greatest purchase I've ever made. Since starting to use it, I no longer have any pain in my wrist. I now realize that with the many viable ergonomic options for mousing that are available, no computer user should be using the very dangerous standard mouse.

Anyway, the mouse that I wholeheartedly recommend is the 3M Ergonomic Optical Mouse:



It is definitely a strange looking mouse, but the strange shape is what makes it work so well. This mouse fixes two problems with traditional mice:

1. Traditional mice force your arm to twist, causing your tendons to rub against each other, which causes inflammation and pain. By letting your arm sit in a much more natural arm-shaking position, the ergonomic mouse prevents this.

2. When using traditional mice, your wrist, with all it's delicate parts, does all the moving. The ergonomic mouse, on the other hand, keeps the wrist straight and the arm becomes the moving part.

So again, I highly recommend this mouse (or a pen tablet) to all computer users, and especially to programmers.



(Note: Just in case anyone thinks I am advertising for 3M, no, I am not in any way sponsored by or affiliated with them.)

16 December 2008

Industrial Strength Application Development in JavaScript

Inspired by the work of Douglas Crockford, I have been developing a JavaScript application using full blown development techniques. JavaScript is definitely a misunderstood and underestimated programming language, and I have found it to be a pretty good hybrid of object-oriented and functional techniques. I have even done some cool things with it that would not be possible in a statically typed language. I have found that with proper unit testing and debugging tools, its dynamic typing has caused me few problems.

So what tools can I recommend for industrial development in JavaScript? Everything below is an absolute must for my needs:

jQuery
  • What it does: Ajax, DOM-modification, and general utility functions
  • As Jeff Atwood pointed out, there is no good reason to write low-level JavaScript to manipulate the DOM with today, now that there are tons of high quality JavaScript libraries to help out.
QUnit
  • What it does: Simple unit testing, compatible with jQuery
  • I tried out a few other unit testing frameworks, but QUnit is the simplest one by far and just gets the job done.
JavaScript Lint
  • What it does: Identifies most textual errors in JavaScript files.
  • Indispensable tool to find that missing semicolon that is causing that weird error.
  • Note for TextMate users: Use the JavaScript Tools bundle instead of downloading it from the official site.
Firebug
  • What it does: Firefox plugin. In addition to excellent DOM manipulation, it makes a great JavaScript debugger.
In Addition, Mozilla's JavaScript Reference is a must for any serious JavaScript developer.

Well, I hope this gets you started. If you have any other suggestions, let me know!