SlideShare a Scribd company logo
Understanding
Prototypal
Inheritance

Guy Royse
@guyroyse
Who
Is
This
Guy?
RULES OF ENGAGEMENT
Get
Your
Hands
Up!
Aren’t Prototypes Hard?
What’s
an
Object?
Object or Not?
varfoo = new Object();
varfoo = {};
varfoo = new String(‘foo’);
varfoo = ‘foo’;
varfoo = new Number(42);
varfoo = 42;

varfoo = new Boolean(false);
varfoo = false;
varfoo = null;
varfoo = undefined;
varfoo = function() {};
varfoo = [1, 2, 3];
Objects are Hashes
varalice = {
name :
‘Alice Bone-crusher’,
class : ‘Fighter’,
level : 5,
hitPoints : 57,
shield : true
};

‘name’

• ‘Alice Bone-crusher’

‘class’

• ‘Fighter’

‘level’

•5

‘hitPoints’ • 57
‘shield’

• true
Reading Properties
alice.name;

// ‘Alice…’

‘name’

• ‘Alice Bone-crusher’

alice*‘class’+;

// ‘Fighter’

‘class’

• ‘Fighter’

‘level’

•5

var property = ‘hitPoints’;
alice[property]; // 57;

‘hitPoints’ • 57
‘shield’

• true
Writing Properties
alice.name =
‘Alice Spellster’;

‘name’

• ‘Alice Spellster’

‘class’

• ‘Wizard’

‘level’

•5

alice*‘class’+ = ‘Wizard’;
var property = ‘hitPoints’;
alice[property] = 24;

‘hitPoints’
‘shield’

• 24

• true
Adding Properties
alice.spell = ‘fireball’;

• ‘Wizard’

‘level’

•5

‘hitPoints’

var property = ‘damage’;
alice*property+ = ‘5d6’;

• ‘Alice Spellster’

‘class’

alice*‘spellLevel’+ = 3;

‘name’

• 24

‘shield’

• true

‘spell’

• ‘fireball’

‘spellLevel’ • 3
‘damage’

• ‘5d6’
Removing Properties
delete alice.shield;

• ‘Wizard’

‘level’

•5

‘hitPoints’

var property = ‘damage’;
delete alice[property];

• ‘Alice Spellster’

‘class’

delete alice*‘spellLevel’+;

‘name’

• 24

‘shield’

• true

‘spell’

• ‘fireball’

‘spellLevel’ • 3
‘damage’

• ‘5d6’
Undefined & Objects
alice.shield; // undefined

‘name’

• ‘Alice Spellster’

‘class’

• ‘Wizard’

‘level’

•5

‘hitPoints’
‘spell’

• 24

• ‘fireball’
Undefined & Objects
alice.shield = undefined;
alice.shield; // undefined

‘name’

• ‘Alice Spellster’

‘class’

• ‘Wizard’

‘level’

•5

‘hitPoints’

• 24

‘spell’

• ‘fireball’

‘shield’

• undefined
Undefined & Objects
delete alice.shield;

‘name’

• ‘Alice Spellster’

‘class’

• ‘Wizard’

‘level’

•5

‘hitPoints’

• 24

‘spell’

• ‘fireball’

‘shield’

• undefined
They’re Just Keys
alice*‘spell level’+ = 3;

• ‘Wizard’

‘level’

•5

‘hitPoints’

alice*‘%foo%’+ = true;

• ‘Alice Spellster’

‘class’

alice*‘1234’+ = 5;

‘name’

• 24

‘spell’

• ‘fireball’

‘spell level’ • 3
‘1234’
‘%foo%’

•5

• true
Objects
Are
Hashes
Prototypes
What’s a Prototype?

child

parent

• firstName : “Bobby”
• hasCandy : true

• firstName : “Bob”
• lastName : “Tables”
How It Works
child.firstName;
child.lastName;
child.hasCandy;

// “Bobby”
// “Tables”
// true

parent.firstName;
parent.lastName;
parent.hasCandy;

// “Bob”
// “Tables”
// undefined

child

parent

• firstName : “Bobby”
• hasCandy : true

• firstName : “Bob”
• lastName : “Tables”
The Prototype Chain

child

parent

grandparent

great_grandparent

• firstName : “Bobby”
• hasCandy : true

• firstName : “Bob”

• firstName : “Robert”
• alive : true

• lastName : “Tables”
• alive: false
Setting the Prototype
var parent = {};
parent.firstName = “Bob”;
parent.lastName = “Tables”;
var child = Object.create(parent);
child.firstName = “Bobby”;
child.hasCandy = true;

child

parent

• firstName : “Bobby”
• hasCandy : true

• firstName : “Bob”
• lastName : “Robertson”
So Why Did
We Think This
Was So Complex?
What’s at the Top?
var parent = new Object();
parent.firstName = “Bob”;
parent.lastName = “Tables”;
var child = Object.create(parent);
child.firstName = “Bobby”;
child.hasCandy = true;

child

parent

Object.prototype

• firstName : “Bobby”
• hasCandy : true

• firstName : “Bob”
• lastName : “Tables”

• toString : function() {}
• valueOf : function() {}
Object.create = function(parent) {
var fn = function() {};
fn.prototype = parent;
return new fn();
};
What’s
a
Class?
Classes
are an
Inconvenient
Fiction
A Simple Class
var Character = function(name, level) {
this.name = name;
this.level = level;
};
varalice = newCharacter(‘Alice’, 5);
Anatomy of Character

Prototype Chain

Object.prototype
toString : function() {}
valueOf : function() {}

function
call : function() {}
apply : function() {}

Character
prototype : {}

var Character = function(name, level) {
this.name = name;
this.level = level;
}

Character.prototype
Now Call New

Prototype Chain

Object.prototype
toString : function() {}
valueOf : function() {}
function
call : function() {}
apply : function() {}
Character
prototype : {}

new

var Character = function(name, level) {
this.name = name;
this.level = level;
}
Character.prototype

alice
name : ‘Alice’
level : 5

varalice = new Character(‘Alice’, 5);
A More Complex Class
var Character = function(name, level) {
this.name = name;
this.level = level;
};
Character.prototype.hitPoints = function() {
return this.level * 5;
};
varalice = new Character(alice, 5);
alice.hitPoints(); // 25
Anatomy of Character

Prototype Chain

Object.prototype
toString : function() {}
valueOf : function() {}

function
call : function() {}
apply : function() {}

Character
prototype : {}

var Character = function(name, level) {
this.name = name;
this.level = level;
}
Character.prototype.hitPoints =
function() { return this.level * 5; };
Character.prototype
hitPoints : function() {}
Now Call New

Prototype Chain

Object.prototype
toString : function() {}
valueOf : function() {}
function
call : function() {}
apply : function() {}
Character
prototype : {}

new

var Character = function(name, level) {
this.name = name;
this.level = level;
Character.prototype.hitPoints =
}
function() {
return this.level * 5;
};
Character.prototype
hitPoints : function() {}
alice
name : ‘Alice’
level : 5

varalice = new Character(‘Alice’, 5);
Object.create = function(parent) {
var fn = function() {};
fn.prototype = parent;
return new fn();
};
Anatomy of Object.create

Prototype Chain

Object.prototype
toString : function() {}
valueOf : function() {}

var fn = function() {};
function
call : function() {}
apply : function() {}

fn
prototype : {}

fn.prototype = parent;

fn.prototype
Object.create = function(parent) {
var fn = function() {};
fn.prototype = parent;
return new fn();
};
Now Call New
Object.prototype
toString : function() {}
valueOf : function() {}

Prototype Chain

var fn = function() {};
function
call : function() {}
apply : function() {}
fn
prototype : {}

fn.prototype = parent;

fn.prototype

child
new
return new fn();
Whew!
In Summary
• Objects are Hashes
• Use Object.create to define prototypes
• Prototypes aren’t hard…
…but the plumbing that makes it work is.
Questions?
Contact Info
Guy Royse
guy@guyroyse.com
@guyroyse
GuyRoyse.com
Image Credits
•
•
•
•

http://www.flickr.com/photos/justin_case/1525042316
http://www.flickr.com/photos/tim_d/155441805
http://www.flickr.com/photos/sybrenstuvel/2335168467
http://www.flickr.com/photos/stawarz/3683017780

More Related Content

KEY
Code Fast, Die Young, Throw Structured Exceptions
PDF
Real world gobbledygook
PDF
Moose workshop
PDF
JavaScript for PHP developers
PDF
Monads asking the right question
KEY
Searching ORM: First Why, Then How
KEY
Code Fast, die() Early, Throw Structured Exceptions
PDF
Javascript the New Parts v2
Code Fast, Die Young, Throw Structured Exceptions
Real world gobbledygook
Moose workshop
JavaScript for PHP developers
Monads asking the right question
Searching ORM: First Why, Then How
Code Fast, die() Early, Throw Structured Exceptions
Javascript the New Parts v2

What's hot (20)

PDF
Sustainable TDD
PDF
Drupal 8: A story of growing up and getting off the island
PDF
JavaScript Primer
PDF
Coffeescript: No really, it's just Javascript
PDF
Why (I think) CoffeeScript Is Awesome
PDF
Go Java, Go!
PDF
Clean code with google guava jee conf
PDF
Google Guava - Core libraries for Java & Android
PDF
JavaScript 1.8.5: New Features Explored
PDF
Proxies are Awesome!
PDF
CoffeeScript
PDF
Scala in Practice
PDF
Google guava overview
PPSX
Symfony2 meets propel 1.5
PDF
Getting Testy With Perl6
PPTX
Java 8 Examples
PDF
Impress Your Friends with EcmaScript 2015
PDF
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
PPTX
Dapper Tool - A Bundle to Make your ECL Neater
PDF
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Sustainable TDD
Drupal 8: A story of growing up and getting off the island
JavaScript Primer
Coffeescript: No really, it's just Javascript
Why (I think) CoffeeScript Is Awesome
Go Java, Go!
Clean code with google guava jee conf
Google Guava - Core libraries for Java & Android
JavaScript 1.8.5: New Features Explored
Proxies are Awesome!
CoffeeScript
Scala in Practice
Google guava overview
Symfony2 meets propel 1.5
Getting Testy With Perl6
Java 8 Examples
Impress Your Friends with EcmaScript 2015
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Dapper Tool - A Bundle to Make your ECL Neater
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Ad

Viewers also liked (6)

PPTX
Programming on Bare Metal: Controlling Circuits with Code
PDF
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
PPTX
The Code Christmas Tree: Selling the Investment for Technical Debt
PPTX
Those Who Know History are Doomed to Watch Others Repeat It
PPTX
Mad Computer Science: Testing COBOL with RSpec
PPTX
Putting the D&D in TDD
Programming on Bare Metal: Controlling Circuits with Code
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
The Code Christmas Tree: Selling the Investment for Technical Debt
Those Who Know History are Doomed to Watch Others Repeat It
Mad Computer Science: Testing COBOL with RSpec
Putting the D&D in TDD
Ad

Similar to Understanding Prototypal Inheritance (20)

PDF
JS Level Up: Prototypes
PPTX
Javascript Prototype Visualized
PDF
JavaScript Inheritance
PPT
Advanced JavaScript
ODP
Basic inheritance in JavaScript
KEY
JavaScript Classes and Inheritance
PDF
Prototype
PDF
JavaScript Essentials
PPT
Advanced Javascript
PPT
Advanced Javascript
PPT
Advanced Javascript
PPTX
Oojs 1.1
PDF
Prototype 120102020133-phpapp02
PDF
Professional JavaScript Development - Creating Reusable Code
PPT
JavaScript In Object Oriented Way
PPTX
Ian 20150116 java script oop
PDF
Writing testable code
PDF
JavaScript OOPs
PPTX
Javascript Prototypal Inheritance - Big Picture
PDF
The prototype property
JS Level Up: Prototypes
Javascript Prototype Visualized
JavaScript Inheritance
Advanced JavaScript
Basic inheritance in JavaScript
JavaScript Classes and Inheritance
Prototype
JavaScript Essentials
Advanced Javascript
Advanced Javascript
Advanced Javascript
Oojs 1.1
Prototype 120102020133-phpapp02
Professional JavaScript Development - Creating Reusable Code
JavaScript In Object Oriented Way
Ian 20150116 java script oop
Writing testable code
JavaScript OOPs
Javascript Prototypal Inheritance - Big Picture
The prototype property

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Cloud computing and distributed systems.
PDF
Approach and Philosophy of On baking technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
The AUB Centre for AI in Media Proposal.docx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
“AI and Expert System Decision Support & Business Intelligence Systems”
Understanding_Digital_Forensics_Presentation.pptx
Chapter 3 Spatial Domain Image Processing.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Cloud computing and distributed systems.
Approach and Philosophy of On baking technology
Building Integrated photovoltaic BIPV_UPV.pdf
Electronic commerce courselecture one. Pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Programs and apps: productivity, graphics, security and other tools
Encapsulation_ Review paper, used for researhc scholars
20250228 LYD VKU AI Blended-Learning.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

Understanding Prototypal Inheritance

Editor's Notes

  • #3: NameTechnologiesCompanyCBusJS
  • #4: 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
  • #5: Poll the audience
  • #6: Not really… in some ways their actually quite easy but first you have to understand objects
  • #7: Poll the audience… tell the smarties to keep quiet
  • #14: Undefined exists, I suspect, because null is empty while undefined is not in the hash, but…
  • #15: …of course you can do this. Which pretty much undermines that premise. Can’t delete by setting property to undefined
  • #20: 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
  • #23: At this point we know how to use prototypal inheritanceNOTE the empty object here
  • #24: Because of the new operator and the prototype property
  • #25: We didn’t have a new operator…. but we had an implied one.object is an implied root, can be accessed via Object.prototype
  • #26: 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
  • #27: Poll the audience
  • #28: 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
  • #29: 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)
  • #32: 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
  • #35: 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
  • #36: We are reassigning the prototype property of the function… yes you can do this.
  • #42: NameTechnologiesCompanyCBusJS