Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 18 | Comments: 72

filter by tags archive

Useful lies about JavaScript Prototype Model

time to read 2 min | 298 words

Note: This is not how it works, but it is close enough that it is a valid mental model for most scenarios.

When I think about JavaScript and its type system, I usually envision objects as hash tables that can carry values or functions. The prototype idea is just an associated hash table, and so on. The moment that I settled on this mental model, it was much easier to grok javascript.

Now, that is a vague explanation if I ever heard one, so let us speak in code:

public class Object
	private readonly Dictionary<string, Procedure> functions 
		= new Dictionary<string, Procedure>();
	private Object prototype;

	public Object Prototype
				prototype = new Object();
			return prototype;
		set { prototype = value; }

	public Procedure this[string name]
			if (functions.ContainsKey(name))
				return functions[name];
			if (prototype != null && prototype.functions.ContainsKey(name))
				return prototype[name];
			throw new InvalidOperationException("No function called " + name);
		set { functions[name] = value; }

This is a simple example of the matter, and here is how you can use it, if you ignore the fact that C# doesn't have any useful duck typing, then this code looks very much like the one that you would write in JavaScript:

Object obj = new Object();
obj["on_change"] = delegate { Console.WriteLine("changed"); };

obj.Prototype["on_load"] = delegate { Console.WriteLine("loaded from prototype"); };


//"overriding" the prototype method
obj["on_load"] = delegate{ Console.WriteLine("loaded from object"); };


obj["missing_method"]();//will throw


Ben Reichelt

I think the Prototype property should be static, right?

IIRC, in javascript if you modify the .prototype property, it applies to all instances of the class, rather than just that instance.

Comment preview

Comments have been closed on this topic.


  1. RavenDB 3.0 New Stable Release - 11 hours from now
  2. Production postmortem: The industry at large - about one day from now
  3. The insidious cost of allocations - 2 days from now
  4. Buffer allocation strategies: A possible solution - 5 days from now
  5. Buffer allocation strategies: Explaining the solution - 6 days from now

And 3 more posts are pending...

There are posts all the way to Sep 11, 2015


  1. Find the bug (5):
    20 Apr 2011 - Why do I get a Null Reference Exception?
  2. Production postmortem (10):
    01 Sep 2015 - The case of the lying configuration file
  3. What is new in RavenDB 3.5 (7):
    12 Aug 2015 - Monitoring support
  4. Career planning (6):
    24 Jul 2015 - The immortal choices aren't
View all series



Main feed Feed Stats
Comments feed   Comments Feed Stats