The Secret Link!
Welcome to…The Secret Link!
In this game, the chain is composed of hashtables (JavaScript objects) related to each other by means of, yes, you guessed it, secret links.
That’s how Douglas Crockford explains JavaScript’s prototypal inheritance in this excellent set of talks now playing at your nearest YUI Theater.
So, given:
var myNewObject = object(youSir);
then, myNewObject has …A Secret Link!…to youSir.
This secret link is followed only when reading an object’s properties. So, say youSir had been defined thusly:
var youSir =
{
name: “Jack B. Nimble”,
grade: “A”,
level: 3
};
then myNewObject.name returns “Jack B. Nimble”. From what hat did myNewObject pull that rabbit, you may ask, after all, myNewObject itself does not have a property called “name!” It’s The Secret Link, stupid! Since looking up “name’s” value directly from myNewObject fails…The Secret Link!…to youSir is used to look up the same property in youSir, which, luckily has that property. Otherwise, youSir’s…Secret Link!…to its parent would have been consulted, applying, lathering, rinsing, and repeating until Object.prototype would’ve been reached, which if it also had no such property would finally have returned…undefined!
However, assignment does not involve…The Secret Link! The assignment,
myNewObject.name = “Johnny B. Goode”;
does not change the value of youSir.name. Instead, it adds the property “name” to myNewObject with the given value, such that mNewObject.name returns “Johnny B. Goode” and youSir.name returns “Jack B. Nimble”.
Pop quiz: What is the result of
myNewObject.level += 1; ?
Answer:
- myNewObject.level does not have a property named “level”, so its…Secret Link!…to youSir is used to look up youSir’s level value, namely 3.
- 3 is added to 1, yielding 4.
- Then a property named “level” is added to myNewObject and assigned the value 4!
That, sir, is JavaScript’s protoypal inheritance in a nutshell, secretly linked hashtables.
on January 29th, 2007 at 11:24 am
Hey, that’s pretty cool. I wonder, though, if there are any implications in how each lookup fails in its traversal up the tree (or hash, rather). Is it merely a check or is it a true exception of lack of a better word? With JS-intensive applications–I’m thinking GMail, Yahoo Mail (beta), and others–could there be performance implications? Just wondering aloud. All in all, though it does get me thinking of how I could use something like this.