Understanding The Complex And Circular Relationships Between Objects In JavaScript

Posted July 28, 2011 at 11:02 AM by Ben Nadel

Tags: Javascript / DHTML

A couple of months ago, when reading JavaScript: The Good Parts by Douglas Crockford, I have to admit that there was some code discussed in the book that really threw my brain through a loop. Specifically, I had a lot of trouble wrapping my head around the ripple effect that took place when methods were added to the Function() prototype. The relationship between JavaScript objects is complex and, at times, circular. I wanted to take a few minutes to just diagram some of the relationships so that I could refer to it in the future when my brain was having a crisis of mental modeling.

In the following diagram, the black lines indicate "inherits from." The pink lines indicate "composes a prototype." When looking at this, it's important to remember that all object constructors (Object, Function, Date, Number, Boolean, etc.) are functions that are an instance of Function. Oh, and yes, that means Function is an instance of itself.... your mind was just blown!


 
 
 

 
The relationship between objects and constructors in the JavaScript language.  
 
 
 

Clearly, the Function() and Object() prototypes are the hugest players in the JavaScript world. Everything ultimately extends the Object() prototype; but, all constructors extend the Function() prototype. This gives both the Object() and Function() prototypes the ability to change just about every object instance in the JavaScript system.

The most interesting part of this family tree is that both Function() and Object() create a circular relationship with their own prototypes. Meaning, a property added to the Function() prototype immediately becomes available in Function() itself. And, a property added to the Object() prototype immediately becomes available in the Object() itself (by way of the Function() prototype). To see what I mean, take a look at this console output:

>>> Object.someProperty
undefined
>>> Object.prototype.someProperty = "set in Object.prototype";
"set in Object.prototype"
>>> Object.someProperty
"set in Object.prototype"

>>> Function.otherProperty
undefined
>>> Function.prototype.otherProperty = "set in Function.prototype";
"set in Function.prototype"
>>> Function.otherProperty
"set in Function.prototype"

This kind of circular relationship doesn't happen anywhere else in the JavaScript world (as far as I can tell). Never do you create a constructor function and have its prototype properties become available within itself. Pretty funky stuff!

Objects (abstractly) are the core of the JavaScript language. And, as you can see, they create a very interesting family tree. In order to help wrap your head around this, I would recommend taking at look at Cody Lindley's new book, JavaScript Enlightenment. Once you fully understand how objects work, you'll really be able to leverage them in some very powerful ways!




Reader Comments

Jul 28, 2011 at 12:51 PM // reply »
1 Comments

Thanks! This was a good reminder of how much I'm taking for granted everytime I write javascript. Good to slow down and really examine what's happening on the language level.

For instance I often do stuff like this:

var bar = function() {
var obj = {
hello: 'Hello World'
// more methods and properties go here
}
return obj;
}

var foo = function() {
this.print = function() {
console.log(this.hello);
}
}

foo.prototype = bar;

foo.print(); // Hello World

I never really slowed down to think about what's actually happening here. A function that creates an object, then returns that object that I then set to the prototype of another function that I'm effectively treating as an object with its own methods and properties. I just take it for granted at this point, but...damn thats trippy.


Jul 28, 2011 at 1:51 PM // reply »
11,238 Comments

@Will,

Yeah, JavaScript is some funky stuff. And, when it comes to returning objects out of a constructor, it can also get more interesting! If you return an object instance, JavaScript will use that as the result of the constructor invocation. However, if you return a non-object (such as a native string or boolean), JavaScript will ignore the return value and simply return the newly instantiated object.

So, it will honor your return value... but only sometimes, depending on what you return.


Jul 29, 2011 at 1:06 AM // reply »
1 Comments

I am relatively new to javascript so yes, my mind is blown. This has helped my understanding, although the more I learn, the more I realize I don't know !!!


Jul 29, 2011 at 8:53 AM // reply »
11,238 Comments

@John,

Luckily, you don't need to really have this stuff in the forefront of your mind when coding. But, when you get into creating your own "classes" and instances, then this kind of understanding becomes a lot more powerful.


Jul 29, 2011 at 10:35 AM // reply »
1 Comments

Thanks for all of your well thought out and written posts!

I've been trying to wrap my brain around this prototype stuff, but since 95% of my time is in PHP, I'm struggling...but hopefully this will help some.


Oct 29, 2011 at 9:15 PM // reply »
11,238 Comments

@Mazz,

Cool my man, hope it helps!


May 20, 2012 at 4:28 AM // reply »
3 Comments

@Will Vaughn I tried your javascript example but got this error:-

foo.print is not a function


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
May 14, 2013 at 6:57 PM
The UX Of Prototyping: Low-Fidelity Is The New High-Fidelity
@Phillip, I'm not sure I follow what you mean? Are you saying that you looked at the list of widgets provided by the jQuery UI and let that be your style guide? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools