I like Steve Yegge’s Prototype Pattern example and decided to whip up a quick proof of concept example.
However, I didn’t really think things through. While it is great for dynamically specifying the behaviour of objects and is an easy solution to Steve’s opinionated elf example, I’m still trying to work out the best way to handle instance variables.
For instance, let’s say I have an AwesomeDragon object. I then want to make an AwesomeDragonImmuneToFire object so I make a new child of the AwesomeDragon (AwesomeDragonImmuneToFire inherits properties from AwesomeDragon) and ‘put’ ‘ImmuneToFire’ as a property with a value of ‘true’. So far so good. Now let’s say I want to send my AwesomeDragon object on a tour of nearby peasant villages. This will involve updating the ‘position’ property of AwesomeDragon. However, the moment I do this AwesomeDragonImmuneToFire will take off as well.
Is the best solution to override instance values upon object creation e.g. immediately ‘put’ the ‘position’ value on AwesomeDragonImmuneToFire to the current ‘get’ value of ‘position’?
Doesn’t it depend how you actually implement the inheritance in your system?
For example, in a JavaScript version of what you describe, the
prototypeforAwesomeDragonImmuneToFirewould normally be an instance of anAwesomeDragon, and since you’d always be working with instances, it wouldn’t matter what you do to any particularAwesomeDragon:In this example, there are no classes and all instances are just instances of
Objectwhich happen to know which function was used to construct them.newis just a bit of syntactic sugar and using StudlyCaps for constructor functions is just a convention for functions which are intended to be used withnew.The key thing is that each object has a chain of prototype objects, which is examined if you try to access an attribute which the object itself doesn’t hold, as per Yegge’s description of what the ‘Properties Pattern’ is.
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model