SlideShare a Scribd company logo
JS Level Up: Prototypes Take your JavaScript to the next level
JavaScript has a very
simple type system
http://bit.ly/1QZ4QVX
JavaScript has a very
simple type system
http://bit.ly/1QZ4QVX
1. Primitive Types
2. Object Types
Primitive Types
http://bit.ly/1QZ4QVX
1. String
2. Number
3. Boolean
4. Undefined
5. Null
Object Types
http://bit.ly/1QZ4QVX
1. Object
2. Array
3. Function
* Some like to say everything is an object
Everything in JavaScript can act like an object
Every object in JavaScript links to a prototype object
console.log( “”.__proto__ === String.prototype ); // true!
That, if you’re wondering, is
pronounced “dunder proto"
Constructor Functions leverage this link

to create reusable interfaces (not UI)
Constructor Functions
• Constructor functions are used
to create new objects. 

• Very useful when creating
multiple instances of a
particular object
var list = new Array( 1, 2, 3 );
list.push( 4 );
// list === [ 1, 2, 3, 4 ]
var list = new Array( 1, 2, 3 );
list.push( 4 );
// list === [ 1, 2, 3, 4 ]
Where did
that push
method
come from?
var list = new Array( 1, 2, 3 );
list.push( 4 );
// list === [ 1, 2, 3, 4 ]
Where did
that push
method
come from?
It’s inherited from Array.prototype!
var list = new Array( 1, 2,
list.push( 4 );
// list === [ 1, 2, 3, 4 ]
new Array( 1, 2, 3 )
var list = new Array( 1, 2,
list.push( 4 );
// list === [ 1, 2, 3, 4 ]
new Array( 1, 2, 3 )
A function is a block of code that is defined

once but can be invoked any number of times.
var list = new Array( 1, 2,
list.push( 4 );
// list === [ 1, 2, 3, 4 ]
new Array( 1, 2, 3 )
Each function has a special this

keyword, the functions invocation context
var list = new Array( 1, 2,
list.push( 4 );
// list === [ 1, 2, 3, 4 ]
new Array( 1, 2, 3 )
Functions used to initialize a new

object are called Constructor Functions
var list = new Array( 1, 2,
list.push( 4 );
// list === [ 1, 2, 3, 4 ]
new Array( 1, 2, 3 )
All functions - because they are objects - have

a prototype property that is a link to the prototype object
So let’s look at an example
function Person ( name ) {
this.name = name;
}
Person.prototype.sayHi = function () {
console.log( “Hi! I’m “, this.name );
}
var vernon = new Person( “Vernon” );
vernon.sayHi(); // Hi! I’m Vernon
Constructor Functions
function Person ( name ) {
this.name = name;
}
Person.prototype.sayHi = function () {
console.log( “Hi! I’m “, this.name );
}
var vernon = new Person( “Vernon” );
vernon.sayHi(); // Hi! I’m Vernon
• Common convention is to
uppercase the first character of
the function name of a
constructor function

• The context of this within the
constructor function is the
newly created object

• No return statement required
Constructor Functions
function Person ( name ) {
this.name = name;
}
Person.prototype.sayHi = function () {
console.log( “Hi! I’m “, this.name );
}
var vernon = new Person( “Vernon” );
vernon.sayHi(); // Hi! I’m Vernon
• We can add custom
functionality to the prototype
object of our function

• This added functionality is
inherited by each instance of
our constructor we create

• The context of methods added
to the prototype object are the
created instance itself
Constructor Functions
function Person ( name ) {
this.name = name;
}
Person.prototype.sayHi = function () {
console.log( “Hi! I’m “, this.name );
}
var vernon = new Person( “Vernon” );
vernon.sayHi(); // Hi! I’m Vernon
• A new object instance is
created by invoking a
constructor function with the
new operator

• Here, we create vernon and
assign is the specified values
as its properties

• So, the value of vernon.name
would be “Vernon”

• We can now create as many
“Person’s” as we want, and
they will all be able to sayHi!
Constructor Functions
function Person ( name ) {
this.name = name; // this === window
}
Person.prototype.sayHi = function () {
console.log( “Hi! I’m “, this.name );
}
var vernon = Person( “Vernon” );
vernon.sayHi(); // Hi! I’m Vernon
• Invoking a constructor function
without the new operator has
unintended side effects

• The context of the newly
created object in the case of a
missing new, is window
Constructor Functions
function Person ( name ) {
if ( !( this instanceof Person ) ) {
return new Person( name );
}
this.name = name;
}
Person.prototype.sayHi = function () {
console.log( “Hi! I’m “, this.name );
}
var vernon = new Person( “Vernon” );
vernon.sayHi(); // Hi! I’m Vernon
• We can protect ourselves from
these side effects by using the
instanceof operator

• instanceof tests whether an
object has the prototype
property of a constructor in its
prototype chain

• Here, we test the context of
our constructor and return the
proper invocation if needed
function Person ( name ) {
this.name = name;
}
Person.prototype.sayHi = function () {
console.log( “Hi! I’m “, this.name );
}
var vernon = new Person( “Vernon” );
vernon.sayHi(); // Hi! I’m Vernon
Person.prototype.sayBye = function () {
console.log( “Bye!” );
}
vernon.sayBye(); // Bye!
function Person ( name ) {
this.name = name;
}
Person.prototype.sayHi = function () {
console.log(
}
var vernon = new Person(
vernon.sayHi(); // Hi! I’m Vernon
Person
console
}
vernon
Prototypal Inheritance
Prototypal Inheritance
• All inheritance in JavaScript is
through the prototype object

• Object.prototype does not
inherit any properties

• All built-in constructors inherit
from Object.prototype
• Best understood by looking at
an example
http://bit.ly/1MNdeGU
Creates a new object with the specified prototype object and properties
Prototypal Inheritance | Object.create()
var obj = {}; // Inherits from Object.prototype
obj.foo = "bar"; // has an own property of foo
var obj2 = Object.create( obj ); // Inherits from obj and Object.prototype
obj2.bar = "baz"; // has an own property of bar
var obj3 = Object.create( obj2 ); // Inherits from obj, obj2 and Object.prototype
obj3.baz = "thud"; // has an own property of baz
console.log( obj3.foo ); // bar
console.log( obj3.bar ); // baz
console.log( obj3.hasOwnProperty( “foo” ) ); // false
var obj = {}; // Inherits from Object.prototype
obj.foo = "bar"; // has an own property of foo
var obj2 = Object.create
obj2.bar = "baz"; // has an own property of bar
var obj3 = Object.create
obj3.baz = "thud"; // has an own property of baz
console.log( obj3.foo ); // bar
console.log( obj3.bar ); // baz
console.log( obj3.hasOwnProperty(
This inheritance lookup is 

done against the prototype chain
Prototypal Inheritance
var obj = {}; // Inherits from Object.prototype
obj.foo = "bar"; // has an own property of foo
var obj2 = Object.create
obj2.bar = "baz"; // has an own property of bar
var obj3 = Object.create
obj3.baz = "thud"; // has an own property of baz
console.log( obj3.foo ); // bar
console.log( obj3.bar ); // baz
console.log( obj3.hasOwnProperty(
We can leverage this to
create scalable objects
Prototypal Inheritance
var obj = {}; // Inherits from Object.prototype
obj.foo = "bar"; // has an own property of foo
var obj2 = Object.create
obj2.bar = "baz"; // has an own property of bar
var obj3 = Object.create
obj3.baz = "thud"; // has an own property of baz
console.log( obj3.foo ); // bar
console.log( obj3.bar ); // baz
console.log( obj3.hasOwnProperty(
Let’s look at 

another example
Prototypal Inheritance
var User = function( details ) {
details = details || {};
this.firstname = details.firstname;
this.lastname = details.lastname;
};
Let’s create a User constructor function
var User = function( details ) {
details = details || {};
this.firstname = details.firstname;
this.lastname = details.lastname;
};
User.prototype.logName = function() {
console.log( this.firstname + " " + this.lastname );
};
Now, we’ll add a logName method to the prototype
var User = function( details ) {
details = details || {};
this.firstname = details.firstname;
this.lastname = details.lastname;
};
User.prototype.logName = function() {
console.log( this.firstname + " " + this.lastname );
};
var john = new User( { firstname: "John", lastname: "Doe" } );
Finally, let’s create an instance of a User
var User = function( details ) { … };
User.prototype.logName = function() { … };
var john = new User( { firstname: "John", lastname: "Doe" } );
var Admin = function( details ) {
this.firstname = details.firstname;
this.lastname = details.lastname;
this.fullaccess = true;
};
Now, let’s add an Admin constructor function
var User = function( details ) { … };
User.prototype.logName = function() { … };
var john = new User( { firstname: "John", lastname: "Doe" } );
var Admin = function( details ) {
this.firstname = details.firstname;
this.lastname = details.lastname;
this.fullaccess = true;
};
Admin.prototype = new User();
Admin.prototype.constructor = Admin;
We can inherit functionality from our User function
var User = function( details ) { … };
User.prototype.logName = function() { … };
var john = new User( { firstname: "John", lastname: "Doe" } );
var Admin = function( details ) {
this.firstname = details.firstname;
this.lastname = details.lastname;
this.fullaccess = true;
};
Admin.prototype = new User();
Admin.prototype.constructor = Admin;
var jane = new Admin( { firstname: "Jane", lastname: "Doe" } );
jane.logName(); // Jane Doe
Our new Admin instance has access to logName
Inheritance and 

the prototype chain
• ECMAScript 6 introduces a
new set of keywords
implementing “classes” in
JavaScript. It’s important to
note that these classes are still
prototype based.

• Object.create is another
method of inheritance

• Do not extend native
prototypes unless you are back
porting newer features of
JavaScript to older engines
http://bit.ly/1MNdeGU
Thanks for listening! @vernonk

More Related Content

What's hot

Moose
MooseMoose
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Nina Zakharenko
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Letusgo 2019 Summer - StringInterpolation and SwiftUI
Letusgo 2019 Summer - StringInterpolation and SwiftUILetusgo 2019 Summer - StringInterpolation and SwiftUI
Letusgo 2019 Summer - StringInterpolation and SwiftUI
정민 안
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
Michael Pirnat
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
Abbas Raza
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Michael Girouard
 
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
Jung Kim
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Stoyan Stefanov
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
Santosh Wadghule
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Kenji Tanaka
 
Symfony2 meets propel 1.5
Symfony2 meets propel 1.5Symfony2 meets propel 1.5
Symfony2 meets propel 1.5
Francois Zaninotto
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger
 
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Data Con LA
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
Nelson Glauber Leal
 

What's hot (20)

Moose
MooseMoose
Moose
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Letusgo 2019 Summer - StringInterpolation and SwiftUI
Letusgo 2019 Summer - StringInterpolation and SwiftUILetusgo 2019 Summer - StringInterpolation and SwiftUI
Letusgo 2019 Summer - StringInterpolation and SwiftUI
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 
Symfony2 meets propel 1.5
Symfony2 meets propel 1.5Symfony2 meets propel 1.5
Symfony2 meets propel 1.5
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011
 
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 

Viewers also liked

Using Node and Grunt to create an awesome workflow
Using Node and Grunt to create an awesome workflowUsing Node and Grunt to create an awesome workflow
Using Node and Grunt to create an awesome workflow
Vernon Kesner
 
Design Systems are Coming... Are you Ready?
Design Systems are Coming... Are you Ready?Design Systems are Coming... Are you Ready?
Design Systems are Coming... Are you Ready?
Vernon Kesner
 
Modular Development with RequireJS
Modular Development with RequireJSModular Development with RequireJS
Modular Development with RequireJS
Vernon Kesner
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
Ryan Anklam
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming Convention
In a Rocket
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting Personal
Kirsty Hulse
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
ux singapore
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Stanford GSB Corporate Governance Research Initiative
 

Viewers also liked (8)

Using Node and Grunt to create an awesome workflow
Using Node and Grunt to create an awesome workflowUsing Node and Grunt to create an awesome workflow
Using Node and Grunt to create an awesome workflow
 
Design Systems are Coming... Are you Ready?
Design Systems are Coming... Are you Ready?Design Systems are Coming... Are you Ready?
Design Systems are Coming... Are you Ready?
 
Modular Development with RequireJS
Modular Development with RequireJSModular Development with RequireJS
Modular Development with RequireJS
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming Convention
 
SEO: Getting Personal
SEO: Getting PersonalSEO: Getting Personal
SEO: Getting Personal
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 

Similar to JS Level Up: Prototypes

The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance
pedro.carvalho
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
Backbone js
Backbone jsBackbone js
Backbone js
rstankov
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
yoavrubin
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
Paweł Dorofiejczyk
 
Bologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinBologna Developer Zone - About Kotlin
Bologna Developer Zone - About Kotlin
Marco Vasapollo
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
marcheiligers
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
Doeun KOCH
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
Daniel Ku
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
Robert Casanova
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
Jussi Pohjolainen
 
JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
Daniel Cousineau
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival Guide
Giordano Scalzo
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 

Similar to JS Level Up: Prototypes (20)

The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Backbone js
Backbone jsBackbone js
Backbone js
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Bologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinBologna Developer Zone - About Kotlin
Bologna Developer Zone - About Kotlin
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival Guide
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 

Recently uploaded

GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 

Recently uploaded (20)

GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 

JS Level Up: Prototypes

  • 1. JS Level Up: Prototypes Take your JavaScript to the next level
  • 2. JavaScript has a very simple type system http://bit.ly/1QZ4QVX
  • 3. JavaScript has a very simple type system http://bit.ly/1QZ4QVX 1. Primitive Types 2. Object Types
  • 4. Primitive Types http://bit.ly/1QZ4QVX 1. String 2. Number 3. Boolean 4. Undefined 5. Null
  • 6. * Some like to say everything is an object Everything in JavaScript can act like an object
  • 7. Every object in JavaScript links to a prototype object console.log( “”.__proto__ === String.prototype ); // true! That, if you’re wondering, is pronounced “dunder proto"
  • 8. Constructor Functions leverage this link
 to create reusable interfaces (not UI)
  • 9. Constructor Functions • Constructor functions are used to create new objects. • Very useful when creating multiple instances of a particular object var list = new Array( 1, 2, 3 ); list.push( 4 ); // list === [ 1, 2, 3, 4 ]
  • 10. var list = new Array( 1, 2, 3 ); list.push( 4 ); // list === [ 1, 2, 3, 4 ] Where did that push method come from?
  • 11. var list = new Array( 1, 2, 3 ); list.push( 4 ); // list === [ 1, 2, 3, 4 ] Where did that push method come from? It’s inherited from Array.prototype!
  • 12. var list = new Array( 1, 2, list.push( 4 ); // list === [ 1, 2, 3, 4 ] new Array( 1, 2, 3 )
  • 13. var list = new Array( 1, 2, list.push( 4 ); // list === [ 1, 2, 3, 4 ] new Array( 1, 2, 3 ) A function is a block of code that is defined
 once but can be invoked any number of times.
  • 14. var list = new Array( 1, 2, list.push( 4 ); // list === [ 1, 2, 3, 4 ] new Array( 1, 2, 3 ) Each function has a special this
 keyword, the functions invocation context
  • 15. var list = new Array( 1, 2, list.push( 4 ); // list === [ 1, 2, 3, 4 ] new Array( 1, 2, 3 ) Functions used to initialize a new
 object are called Constructor Functions
  • 16. var list = new Array( 1, 2, list.push( 4 ); // list === [ 1, 2, 3, 4 ] new Array( 1, 2, 3 ) All functions - because they are objects - have
 a prototype property that is a link to the prototype object
  • 17. So let’s look at an example function Person ( name ) { this.name = name; } Person.prototype.sayHi = function () { console.log( “Hi! I’m “, this.name ); } var vernon = new Person( “Vernon” ); vernon.sayHi(); // Hi! I’m Vernon
  • 18. Constructor Functions function Person ( name ) { this.name = name; } Person.prototype.sayHi = function () { console.log( “Hi! I’m “, this.name ); } var vernon = new Person( “Vernon” ); vernon.sayHi(); // Hi! I’m Vernon • Common convention is to uppercase the first character of the function name of a constructor function • The context of this within the constructor function is the newly created object • No return statement required
  • 19. Constructor Functions function Person ( name ) { this.name = name; } Person.prototype.sayHi = function () { console.log( “Hi! I’m “, this.name ); } var vernon = new Person( “Vernon” ); vernon.sayHi(); // Hi! I’m Vernon • We can add custom functionality to the prototype object of our function • This added functionality is inherited by each instance of our constructor we create • The context of methods added to the prototype object are the created instance itself
  • 20. Constructor Functions function Person ( name ) { this.name = name; } Person.prototype.sayHi = function () { console.log( “Hi! I’m “, this.name ); } var vernon = new Person( “Vernon” ); vernon.sayHi(); // Hi! I’m Vernon • A new object instance is created by invoking a constructor function with the new operator • Here, we create vernon and assign is the specified values as its properties • So, the value of vernon.name would be “Vernon” • We can now create as many “Person’s” as we want, and they will all be able to sayHi!
  • 21. Constructor Functions function Person ( name ) { this.name = name; // this === window } Person.prototype.sayHi = function () { console.log( “Hi! I’m “, this.name ); } var vernon = Person( “Vernon” ); vernon.sayHi(); // Hi! I’m Vernon • Invoking a constructor function without the new operator has unintended side effects • The context of the newly created object in the case of a missing new, is window
  • 22. Constructor Functions function Person ( name ) { if ( !( this instanceof Person ) ) { return new Person( name ); } this.name = name; } Person.prototype.sayHi = function () { console.log( “Hi! I’m “, this.name ); } var vernon = new Person( “Vernon” ); vernon.sayHi(); // Hi! I’m Vernon • We can protect ourselves from these side effects by using the instanceof operator • instanceof tests whether an object has the prototype property of a constructor in its prototype chain • Here, we test the context of our constructor and return the proper invocation if needed
  • 23. function Person ( name ) { this.name = name; } Person.prototype.sayHi = function () { console.log( “Hi! I’m “, this.name ); } var vernon = new Person( “Vernon” ); vernon.sayHi(); // Hi! I’m Vernon Person.prototype.sayBye = function () { console.log( “Bye!” ); } vernon.sayBye(); // Bye!
  • 24. function Person ( name ) { this.name = name; } Person.prototype.sayHi = function () { console.log( } var vernon = new Person( vernon.sayHi(); // Hi! I’m Vernon Person console } vernon Prototypal Inheritance
  • 25. Prototypal Inheritance • All inheritance in JavaScript is through the prototype object • Object.prototype does not inherit any properties • All built-in constructors inherit from Object.prototype • Best understood by looking at an example http://bit.ly/1MNdeGU
  • 26. Creates a new object with the specified prototype object and properties Prototypal Inheritance | Object.create() var obj = {}; // Inherits from Object.prototype obj.foo = "bar"; // has an own property of foo var obj2 = Object.create( obj ); // Inherits from obj and Object.prototype obj2.bar = "baz"; // has an own property of bar var obj3 = Object.create( obj2 ); // Inherits from obj, obj2 and Object.prototype obj3.baz = "thud"; // has an own property of baz console.log( obj3.foo ); // bar console.log( obj3.bar ); // baz console.log( obj3.hasOwnProperty( “foo” ) ); // false
  • 27. var obj = {}; // Inherits from Object.prototype obj.foo = "bar"; // has an own property of foo var obj2 = Object.create obj2.bar = "baz"; // has an own property of bar var obj3 = Object.create obj3.baz = "thud"; // has an own property of baz console.log( obj3.foo ); // bar console.log( obj3.bar ); // baz console.log( obj3.hasOwnProperty( This inheritance lookup is 
 done against the prototype chain Prototypal Inheritance
  • 28. var obj = {}; // Inherits from Object.prototype obj.foo = "bar"; // has an own property of foo var obj2 = Object.create obj2.bar = "baz"; // has an own property of bar var obj3 = Object.create obj3.baz = "thud"; // has an own property of baz console.log( obj3.foo ); // bar console.log( obj3.bar ); // baz console.log( obj3.hasOwnProperty( We can leverage this to create scalable objects Prototypal Inheritance
  • 29. var obj = {}; // Inherits from Object.prototype obj.foo = "bar"; // has an own property of foo var obj2 = Object.create obj2.bar = "baz"; // has an own property of bar var obj3 = Object.create obj3.baz = "thud"; // has an own property of baz console.log( obj3.foo ); // bar console.log( obj3.bar ); // baz console.log( obj3.hasOwnProperty( Let’s look at 
 another example Prototypal Inheritance
  • 30. var User = function( details ) { details = details || {}; this.firstname = details.firstname; this.lastname = details.lastname; }; Let’s create a User constructor function
  • 31. var User = function( details ) { details = details || {}; this.firstname = details.firstname; this.lastname = details.lastname; }; User.prototype.logName = function() { console.log( this.firstname + " " + this.lastname ); }; Now, we’ll add a logName method to the prototype
  • 32. var User = function( details ) { details = details || {}; this.firstname = details.firstname; this.lastname = details.lastname; }; User.prototype.logName = function() { console.log( this.firstname + " " + this.lastname ); }; var john = new User( { firstname: "John", lastname: "Doe" } ); Finally, let’s create an instance of a User
  • 33. var User = function( details ) { … }; User.prototype.logName = function() { … }; var john = new User( { firstname: "John", lastname: "Doe" } ); var Admin = function( details ) { this.firstname = details.firstname; this.lastname = details.lastname; this.fullaccess = true; }; Now, let’s add an Admin constructor function
  • 34. var User = function( details ) { … }; User.prototype.logName = function() { … }; var john = new User( { firstname: "John", lastname: "Doe" } ); var Admin = function( details ) { this.firstname = details.firstname; this.lastname = details.lastname; this.fullaccess = true; }; Admin.prototype = new User(); Admin.prototype.constructor = Admin; We can inherit functionality from our User function
  • 35. var User = function( details ) { … }; User.prototype.logName = function() { … }; var john = new User( { firstname: "John", lastname: "Doe" } ); var Admin = function( details ) { this.firstname = details.firstname; this.lastname = details.lastname; this.fullaccess = true; }; Admin.prototype = new User(); Admin.prototype.constructor = Admin; var jane = new Admin( { firstname: "Jane", lastname: "Doe" } ); jane.logName(); // Jane Doe Our new Admin instance has access to logName
  • 36. Inheritance and 
 the prototype chain • ECMAScript 6 introduces a new set of keywords implementing “classes” in JavaScript. It’s important to note that these classes are still prototype based. • Object.create is another method of inheritance • Do not extend native prototypes unless you are back porting newer features of JavaScript to older engines http://bit.ly/1MNdeGU