Introduction
Objects
Instances
Local
Inheritance
Prototypes
Override
Overwrite
Protection
Arguments
Constructors
Methods
Proto
Arguments Array
Callee
New
Extend
Super
Glossary
 
 
Debreuil Digital Works © 2001
 

Overriding

We now have a model where all Dogs have four legs, and some dogs have puffyHair. Does our model break if yeller slips while using a bandsaw - and loses a leg? We don't want to make the change Dog.prototype.legs = 3, because that would affect all dogs (unless we take the bandsaw to the others, hmm...). If we go back to our sheets of glass model, we can see the best place to record this tragic turn of events would be on yeller's first sheet - just the way fido stores information about his personal haircut. That is logical enough, after all it's yeller's personal misfortune, it's not a species-wide tragedy. What happens, though, if you modify yeller's legs property, by saying:

yeller.legs = 3? 

Won't that simply change the value of Dog.prototype.legs to 3? Happily for Dog-kind, no. Actionscript will not let an instance casually change its prototype (more on this in the Protection unit). You are protected from yourself. It's safe to use cutlery again.

But wait... Does yeller not have two "legs" properties now: one in his instance and one in his prototype? Let's look again at our sheets of glass model. There is indeed now a paper that says legs = 4 on the prototype sheet, and one that says legs = 3 on his instance sheet. There is a funny thing about this glass though - if two pieces of paper have the same property name, they line up (maybe that's why it's so expensive!). So these two papers line up exactly, and what do you see? The first (and topmost - or instance -) one, of course, and that's what you get: yeller.legs == 3. Here is what the code looks like:

Dog = function( ){}
Dog.prototype.legs = 4;

yeller = new Dog( );
yeller.legs = 3;

That makes sense, even if you read it in plain old gibberish. 'Dogs have four legs, but yeller has three legs'. This is called overriding. When two properties have the same name, the one closest to the instance is returned. This is just how it works on layers of glass, if one thing covers another, you only see the one closest to you. Of course in glass, if you remove the front object then you can see the back one again. Is this how it works with the prototype? Is the original property still there? Yes it is, just delete the one in front and you will see it. Here's how:

trace( yeller.legs ); // 3 - from the instance
delete( yeller.legs );
trace( yeller.legs ); // 4 - from the prototype

You can see from this example that yeller's personal legs property was just 'blocking the view', or overriding the Dog.prototype.legs property. You could read this as 'yeller used to have three legs, but now (through the miracle of modern medicine) he has four legs like other dogs'. Once again, old yeller brings a tear to the eye.

Prototypes < < Home > > Overwriting