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: 6,026 | Comments: 44,842

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.


No future posts left, oh my!


  1. Technical observations from my wife (3):
    13 Nov 2015 - Production issues
  2. Production postmortem (13):
    13 Nov 2015 - The case of the “it is slow on that machine (only)”
  3. Speaking (5):
    09 Nov 2015 - Community talk in Kiev, Ukraine–What does it take to be a good developer
  4. Find the bug (5):
    11 Sep 2015 - The concurrent memory buster
  5. Buffer allocation strategies (3):
    09 Sep 2015 - Bad usage patterns
View all series


Main feed Feed Stats
Comments feed   Comments Feed Stats