Understanding JavaScript: Inheritance and the prototype chain

This is the first post in a series on JavaScript. In this post I’m going to explain how JavaScript’s prototype chain works, and how you can use it to achieve inheritance.

First, it’s important to understand that while JavaScript is an object-oriented language, it is prototype-based and does not implement a traditional class system. Keep in mind that when I mention a class in this post, I am simply referring to JavaScript objects and the prototype chain – more on this in a bit.

Almost everything in JavaScript is an object, which you can think of as sort of like associative arrays – objects contain named properties which can be accessed with obj.propName or obj['propName']. Each object has an internal property called prototype, which links to another object. The prototype object has a prototype object of its own, and so on – this is referred to as the prototype chain. If you follow an object’s prototype chain, you will eventually reach the core Object prototype whose prototype is null, signalling the end of the chain.

So what is the prototype chain used for? When you request a property which the object does not contain, JavaScript will look down the prototype chain until it either finds the requested property, or until it reaches the end of the chain. This behaviour is what allows us to create “classes”, and implement inheritance.

Don’t worry if this doesn’t make sense yet. To see prototypes in action, let’s take a look at the simplest example of a “class” within JavaScript, which is created with a function object:

function Animal() {}

var animal = new Animal();

We can add properties to the Animal class in two ways: either by setting them as instance properties, or by adding them to the Animal prototype.

function Animal(name) {
    // Instance properties can be set on each instance of the class
    this.name = name;
}

// Prototype properties are shared across all instances of the class
Animal.prototype.speak = function() {
    console.log("I'm a " + this.name);
};

var animal = new Animal('Cat');
animal.speak(); // I'm a Cat

The structure of the Animal object becomes clear when we inspect it in the console. We can see that the name property belongs to the object itself, while speak is part of the Animal prototype.

Animal Prototype

Now let’s look at how we can extend the Animal class to create a Cat class:

function Cat(name) {
    this.name = name;
}

Cat.prototype = new Animal();

cat = new Cat('Cat');
cat.speak(); // I'm a Cat

What we are doing here is setting Cat‘s prototype to an instance of the Animal object, so that Cat inherits all of Animal's properties. Let’s take a look at the Cat object to get a better view of what’s going on.

Cat Prototype
The Cat object has its own name instance property, like we expected. When we look at the object’s prototype we see that it has also inherited Animal‘s name instance property as well as the speak prototype property. This is where the prototype chain comes in – when we request cat.name, JavaScript finds the name instance property and doesn’t bother going down the prototype chain. However when we request cat.speak, JavaScript has to travel down the prototype chain until it finds the speak property inherited from Animal.

At this point I would recommend going through a few slides of John Resig’s JavaScript Ninja as they go into more detail about how JavaScript prototypes work, and provide some good interactive examples.

Stop posting jobs for “hackers”

I understand what people mean when they say that they want to hire a hacker. It means that they want to hire a developer; probably one who is enthusiastic and good at solving problems. The thing is, to me, the term hacker is no different from terms like rock star or ninja. When I see these terms in a job advertisement, a few red flags are raised in my mind:

You’re probably a start-up

This isn’t necessarily a bad thing, but it often means that whoever posted the job advertisement has a lack of technical knowledge, which probably also means…

You don’t actually know what kind of developer you want

Hacker, rock star, ninja – these don’t actually mean anything in the context of programming. Do you want a front-end web developer who can make complex JavaScript apps, or a Ruby developer with a working knowledge in system administration, or do you just want an all-rounder? If the title of your job advertisement has no context, I (and many other people) will simply ignore it.

The job requires more than one person

You really need 2 or 3 people for this job, but budgeting concerns have forced you to go for a single super-developer instead. This also leads me to believe that the job will have ill-defined requirements, and that I’m likely to be over-worked and under-paid.

For the most part, I think that if you find yourself posting an ad for a hacker, rock star, or ninja, you should take it as a sign that you need to re-think your hiring requirements. Take a little extra time to figure out what kind of developer you really want to hire, and write the advertisement accordingly.

Setting up your editor

Setting up your editor correctly can make working with other developers much less painful (for everybody). Below are some things that I believe every developer should do when editing source code. Any good IDE or editor should have settings to do these things automatically – the points below are paired with their Sublime Text 2 setting.

  • Trim trailing whitespace – "trim_trailing_white_space_on_save": true
  • Always use Unix line endings (LF) - "default_line_ending": "unix"
  • Ensure files end with a new line – "ensure_newline_at_eof_on_save": true
  • Automatically detect indentation style – "detect_indentation": true
  • Or, failing the above, have a way to quickly switch between indentation styles.

Solving “502 Bad Gateway” with nginx & php-fpm

After upgrading php-fpm, my PHP-based sites were returning “502 Bad Gateway” errors. Here’s how I managed to solve it.

Check to make sure that php-fpm is running with ps auxww | grep php – if you can’t see any php-fpm processes in the output, then you may need to re-install php-fpm. If php-fpm is running okay, then skip this first step.

sudo apt-get remove php5 php5-cgi php5-fpm
sudo apt-get install php5 php5-cgi php5-fpm

The thing to notice here is that the order in which you install the packages is important. In the past I have found that installing them in the wrong order causes the packages to be configured incorrectly.

Next, get php-fpm to listen on the correct host/port. In /etc/php5/fpm/pool.d/www.conf change the following line from:

listen = /var/run/php5-fpm.sock

To:

listen = 127.0.0.1:9000

Restart php-fpm with sudo /etc/init.d/php-fpm restart and everything should work normally again.

Sublime Text 2 packages for web development

Coming from PhpStorm (a full-featured IDE), I felt that Sublime Text 2 was missing a few useful features. Luckily, one of the great things about Sublime is that it can be easily extended with plugins and packages. Perhaps the most useful package for Sublime is Sublime Package Control, which allows you to easily install and manage packages (it can even uninstall itself – über meta).

Below are some Sublime Text 2 packages that I have found to be useful for web development.

  • All Autocomplete extends the Sublime Text 2 autocompletion to find matches in all open files.
  • ApacheConf.tmLanguage provides ApacheConf syntax highlighting (for .htaccess, vhosts, etc).
  • DocBlockr simplifies and automates writing DocBlock comments in many languages including PHP and Javascript.
  • Sass and LESS both provide syntax highlighting for the Sass and LESS dynamic stylesheet languages. Compass also provides a watch/build system for Sass.
  • SideBarEnhancements provides many useful enhancements to the default Sublime Text 2 sidebar, including Copy Path and Open With…
  • SublimeCodeIntel is a full-featured code intelligence engine that provides smart autocomplete and jump-to-symbol functionality.
  • SublimeLinter automatically runs your code through a linter and highlights lines that it deems to contain (potential) errors. SublimeLinter has built-in linters for most popular languages.

September 4: Looking back on the Christchurch earthquakes

In the early hours of 4 September 2010, I was sound asleep in my house on Mount Pleasant hill in Christchurch, New Zealand. At 4:35am I was woken by a deep rumbling sound. Seconds later, the floor and walls began to shake as my house was rocked back and forth on its foundations. I scrambled out of bed and hid in a doorway until the shaking stopped. After checking that my family was okay, I went upstairs and stepped onto the balcony to look out over Christchurch. The city was silent save for a few car alarms, and it was in this relative quiet that I came to understand the significance of this event. I didn’t realise it then, but that earthquake would become a catalyst for change in my life. Continue reading

Programming Books and Resources

This post is a list of programming-related books that I intend to read at some point (in no particular order).

And some other resources that aren’t books:

The man who could turn his feet into roller blades

Few people know about my ability to transform my feet into roller blades. Doctors around the world are perplexed, and also impressed. Biologists debate whether such a transformation is even possible.

I casually slide into the biologist debating hall and take a seat near the front. People are staring at my roller-feet, but I don’t care. I put my shades on. Continue reading

Testing Laravel Controllers

There are a two main things that tripped me up while I was writing functional tests for my Laravel controllers: POST requests, and session state.

Laravel’s Controller class has the call() method, which essentially makes a GET request to a controller method. In order to make POST requests, it’s necessary to inject some extra parameters into the HttpFoundation components. To make this easier, I created a ControllerTestCase class with convenient get() and post() methods: Continue reading