Posts

Showing posts from 2012

Introduction to Inheritance and the Prototype Chain in JavaScript (with diagrams)

Image
In this post I’m going to demonstrate how the JavaScript prototype chain works by example, starting with the creation of basic objects and functions and working up to inheritance.  To do this I’ll execute commands in the Chrome JavaScript Console, and then I’ll use diagrams to show the state of the system.  To follow along, open the Chrome JavaScript Console.  Start Chrome and then press Ctrl+Shift+J (or Cmd+Option+J on a Mac). Objects and the Prototype Chain First I’ll create an empty object, x: > var x = {} > dir(x) // used to inspect x. What’s going on here? - I’ve created an object, x, and it has a single property, __proto__. - The value of __proto__ is set to Object.prototype. I can type the following statement into the console to verify the value of x.__proto__: > x.__proto__ === Object.prototype // true So what is this __proto__ property, and why does x have it?  In JavaScript, every object is created with a __proto__ property, and its value is