Ayende @ Rahien

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

ayende@ayende.com

+972 52-548-6969

, @ Q c

Posts: 5,972 | Comments: 44,509

filter by tags archive

Useful lies about JavaScript Prototype Model


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
	{
		get
		{
			if(prototype==null)
				prototype = new Object();
			return prototype;
		}
		set { prototype = value; }
	}

	public Procedure this[string name]
	{
		get
		{
			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"); };


obj["on_change"]();
obj["on_load"]();

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

obj["on_load"]();

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

Comments

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.

FUTURE POSTS

  1. Paying the rent online - 2 hours from now
  2. Reducing parsing costs in RavenDB - about one day from now

There are posts all the way to Aug 04, 2015

RECENT SERIES

  1. Production postmortem (5):
    29 Jul 2015 - The evil licensing code
  2. Career planning (6):
    24 Jul 2015 - The immortal choices aren't
  3. API Design (7):
    20 Jul 2015 - We’ll let the users sort it out
  4. What is new in RavenDB 3.5 (3):
    15 Jul 2015 - Exploring data in the dark
  5. The RavenDB Comic Strip (3):
    28 May 2015 - Part III – High availability & sleeping soundly
View all series

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats