Frightened and confused by the term "prototype"? Tired of praying that there's some plugin for a framework that will do exactly what you need to do? Unlock a whole new world of interactivity with object-oriented JavaScript programming.
Web was a scary placeBrowser compatibility and features all over the mapDevs hop from site to site grabbing snippets of code
JS libraries emerge several years agoSmooth over cross browser differencesMake complex behavior easyProvide frameworks for enhancement
New dependency on libraries and plugins is growingDevs spend a lot of time… (series)
Searching for a JS library extension that does what they need
Changing site to fit what the extension does
Brute-force coding requirements back in
Live in fear of repeating it allwhen make updateson the next project
One of JS most powerful featues goesUnusedIgnoredMisunderstoodAnd it can help
JS is OOP language
Objects are containers forProperties - DataMethods - BehaviorsWork with objects all the time
Template for properties + methodsWork with prototypes every dayEven if you don’t realize itDate, Array, etc
Code you writeCode loaded in memory
Easy to…BuildModifyExpand on complex interactions
Reference point that serves as basis for an objectTo understand prototypeNeed to understand property lookup chain
Simple exampleCreate a date var named “instance”Define a new property on the varCall several methods
PLC for instance var looks like thisInstance prototype = DateDate prototype = ObjectJS uses PLC to find values of referenced properties
Look up instance.fooJS finds it on the var itselfStops looking
Lookup instance.getTimeDoesn’t find it on the varFinds it on DateStops looking
Lookup instance.hasOwnPropertyDoesn’t find it on varDoesn’t find it on DateFinds it on Object
Prototypes are put together different than most
More complicated exampleRex is var instance of PoodlePoodle prototype = DogDog prototype = Object
Closer look at DogFunctionAll functions have prototype propertyPrototype defaults to ObjectConstructor is Function paired with NEW operatorUsed to create instances
Dog’s prototype property used to build the templateFunctions on a prototype are methodsNon-functions on a prototype are propertiesAnything defined on function’s prototype available to instances
Poodle is second typeFunction, just like DogInheritanceSet Poodle.prototype to new instance of DogCreates link between Poodle and Dog in PLCCreate properties on Poodle.prototypeAvailable to instances of Poodle
Rex is instance of PoodleProperty “name” defined on rex – instance propertyHas access to all of Poodle’s prototype propertiesAnd to other properties up PLC
Probably recognize THIS operatorLook at how THIS interacts with prototypeIn example:Socks and fluffy both instances of CatCat inherits from Object
When call socks.speakFinds speak property on Cat.prototypeInside of speak, encounter THISProperties on THIS walk PLC starting at instanceGreeting not a property of socks instanceGreeting is a property of Cat prototype
When call fluffy.speakSpeak function found on Cat.prototype, same as socksUnlike socks, fluffy has own greeting propertylookup stops at instance
Functions have call method that lets set execution contextTHIS operator refers back to execution context
When sayFoo called with exec context objTHIS = obj
Calling a method on an instance is same asUsing CALL to supply instance as exec context prototype method
Shown some basic examples so far, but don’t really take advantageDive deeper into inheritance
In example:Container type hasarray that it can store items inMethod to add itemsinherits from ObjectLimitedContainerInherits from ContainerChanges inherited behavior to limit how many items can be in array
Behavior in Container constructor creates items arrayTo get LC to also have that behaviorCALL Container constructor with THIS as exec context within LC constructor
Container’s addItem method just pushes into arrayWant to set a limit to how many items can be in arrayDefine new addItem method on LC prototypeThe new addItem is higher in the PLC, so it will be found before old oneAdd logic into new method to throw error if there are too many itemsCALL Container’s addItem method with THIS as exec context to get original behavior
Have kind of a patchwork natureCan take advantage of that to bring together lots of complicated behaviors
In example, CatDog borrows behavior from Cat and DogCat instances are furious when call swim methodDog instances are delightedCatDog is both delighted and furious when you call its swim method
May have noticed an issue in earlier examples
Have two types: Parent and ChildChild inherits from parent
When Child linked to ParentParent constructor is calledParent constructor has undesirable behaviorAlert goes off when set up inheritance
Get around issue with a simple helper function
Helper:Creates intermediate function that does nothingAssigns parent prototype to itInstantiates intermediate as prototypeBecause prototype is same b/t intermediate and parent, PLC stays intactAlso define constructor on child while we’re at itNo more undesirable behavior
Prototypes have never been accused of being very prettyBut they are very powerful
Up to now, haven’t had any real world examplesLet’s see what they can really doEXAMPLEPretty standard HTML formCommon problem is validating a formLet’s do it with prototypes!
Helper:Creates intermediate function that does nothingAssigns parent prototype to itInstantiates intermediate as prototypeBecause prototype is same b/t intermediate and parent, PLC stays intactAlso define constructor on child while we’re at itNo more undesirable behavior
Helper:Creates intermediate function that does nothingAssigns parent prototype to itInstantiates intermediate as prototypeBecause prototype is same b/t intermediate and parent, PLC stays intactAlso define constructor on child while we’re at itNo more undesirable behavior
And do a really good job of itStart to get into trouble when depend totally on the libraryStart to get into bad trouble when depending totally on plugins
Easy to…BuildModifyExpand on complex interactions
Help you design the interactionthe way it needs to workand in a reusable, extensible way that plays well with others