This document discusses prototypal inheritance in JavaScript. It explains that objects are hashes, and prototypes allow objects to inherit properties from parent objects. The document demonstrates how to define prototypes using Object.create, and shows how this allows child objects to access properties from parents in the prototype chain even if they are not directly defined on the child. It also discusses how classes are an "inconvenient fiction" in JavaScript and are simply constructor functions with methods added to the prototype.
Rules of EngagementInterrupt me-80/20 ruleWe’re gonna go deep (up to the edge of what I know)- not going to talk about browsers – this is about the language
Poll the audience
Not really… in some ways their actually quite easy but first you have to understand objects
Poll the audience… tell the smarties to keep quiet
Undefined exists, I suspect, because null is empty while undefined is not in the hash, but…
…of course you can do this. Which pretty much undermines that premise. Can’t delete by setting property to undefined
Every object has a prototype (which is another object)Note I said “has a” and not “is a” – this is compositionIf it ain’t found in the child, look in the parent
At this point we know how to use prototypal inheritanceNOTE the empty object here
Because of the new operator and the prototype property
We didn’t have a new operator…. but we had an implied one.object is an implied root, can be accessed via Object.prototype
It’s inside of the definition of Object.create as well.new suggests classes and classical inheritance while prototype suggests that stuff we were talking about earlierThis doesn’t quite jive, So let’s look at classes
Poll the audience
Not real, a confusing layer on top of an otherwise pleasant functional language.People always contradict me on this point… but psuedo classes aren’t classes… that’s why the psuedo is there
Where’s the word class… looks like a function to me. But, we do have the keyword newIt’s really a constructor function the makes objects … classes are templates. JavaScript doesn’t have those, just these functions that you call with new(and make sure you call new ‘cuz otherwise, bad stuff can happen)
NOTE the function on Character.prototypeWe are adding something to the prototype… it’s just an object, we can do that easily.In fact you can do this with any “class” in Javascript including Number, Array, Boolean, String, and Object
Remember this guy? Now we have the tools to understand how he works…Note that we are *replacing* the prototype of this constructor function as opposed to adding to it or just taking it as isAlso note the grand utility of the fn function … it doesn’t do much .. In fact, it’s just there to give use something with a prototype property we can call new against
We are reassigning the prototype property of the function… yes you can do this.