I think I now actually understand JavaScript objects

Over the last week or so, I've been writing a lot of NodeJS-based JavaScript, and in doing so I realised I didn't really have a picture of how the object model actually fits together. So I did some reading, and now I'm pretty sure I get it.

The articles I read are linked at the bottom of the post, but often code is clearer to read than paragraphs of explanation. I've thrown together some implementations of the key players in the javascript object model that mirror what the actual engine is doing under the hood.

The following examples should explain the prototype chain, how it's assembled and how it's interacted with - I've added some console output to the loops so we can see what's happening as they're called.

The code below assumes that its running under an ECMAScript 5 environment, so thats the latest versions of Safari, Chrome and Firefox - as well as NodeJS. It takes advantage of Object.create and Object.getPrototypeOf, these are the standardised versions of messing around with the __proto__ property.

And to see it in action:

Which produces:

> node demo.js 
john instance_of Employee
Trying to match Employee.prototype
Comparing to Retired.prototype
Comparing to Employee.prototype
true

john instance_of Array
Trying to match Array.prototype
Comparing to Retired.prototype
Comparing to Employee.prototype
Comparing to Person.prototype
Comparing to Object.prototype
false

new_instance(Person, 'john') instanceof Person
true

new_instance(Employee, 'boss', 'john') instanceof Employee
true

get_attribute(john, 'role')
Looking on object directly
Boss

get_attribute(john, 'greeting')
Looking on object directly
Looking on Retired.prototype
Looking on Employee.prototype
Welcome to work

call_method(john, 'greet')
Looking on object directly
Looking on Retired.prototype
Looking on Employee.prototype
Looking on Person.prototype
Hello John

If you'd like to have a play with these functions without firing up NodeJS, here's the obligatory JSFiddle: http://jsfiddle.net/88je8/1/

See also: