SlideShare a Scribd company logo
Object Oriented 
Javascript
A pragmatic introduction
March 2015
Ibán Martínez
iban@nnset.com
www.openshopen.com
We will take a look to :
­ Object­oriented programming basic 
concepts. 
­ Javascript Object creation.
https://developer.mozilla.org/en­US/docs/Web/JavaScript/Introduction_to_Object­Oriented_JavaScript
Object oriented essentials
(no javascript specific)
Object­oriented programming is a 
programming paradigm that uses 
abstraction to create models based on 
the real world. It uses several 
techniques from previously 
established paradigms, including 
modularity, polymorphism, and 
encapsulation.
https://developer.mozilla.org/en­US/docs/Web/JavaScript/Introduction_to_Object­Oriented_JavaScript
Object oriented essentials
(no javascript specific)
ClassClass : Defines the characteristics of the object. It is a 
template definition of properties and methods of an object.
ObjectObject : An Instance of a class.
PropertyProperty : An object characteristic, such as color.
MethodMethod : An object capability, such as walk. It is a 
subroutine or function associated with a class.
Object oriented essentials
(no javascript specific)
ClassClass
class ShoppingCart {
   [...]
}
ObjectObject
$myCart = new ShoppingCart();
PropertyProperty
class ShoppingCart {
   public $ownerName = 'Mike';
}
MethodMethod
classclass ShoppingCart { ShoppingCart {
   public $ownerName = 'Mike';
   public function addProduct(Product $product){
     $this­>appendProductToShoppingList($product); 
     $this­>updateTotalPrice();
   }
}
Object oriented essentials
(javascript specifics)
Prototype­based programming is a style of 
object­oriented programming that doesn't make 
use of classes. Instead, behavior reuse (known 
as inheritance in class­based languages) is 
accomplished through a process of decorating 
(or expanding upon) existing objects which 
serve as prototypes. This model is also known 
as classless, prototype­oriented, or instance­
based programming.
Object oriented essentials
(javascript specifics)
Prototype­based programming is a style of 
object­oriented programming that doesn't make 
use of classes. Instead, behavior reuse (known 
as inheritance in class­based languages) is 
accomplished through a process of decorating 
(or expanding upon) existing objects which 
serve as prototypes. This model is also known 
as classless, prototype­oriented, or instance­
based programming.
JavaScript is a prototype­based 
language which contains no class 
statement.
Object oriented essentials
(javascript specifics)
What is an 'object' for Javascript?
typeof({});
 => 'object'
typeof([]);
 => 'object'
typeof(null);
 => 'object'
typeof(new String());
 => 'object'
typeof(new Number());
 => 'object'
typeof(new Boolean());
 => 'object'
typeof(new Object());
 => 'object'
In JavaScript, almost 
everything is an object.
Object creation
in Javascript
Objects creation
new & Object.create()
Two common ways to create objects are using “new”“new” or 
“Object.create()”“Object.create()” directives.
https://developer.mozilla.org/en­US/docs/Web/JavaScript/Guide/Working_with_Objects
https://developer.mozilla.org/en­US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
Objects creation
new & Object.create()
new
var myCar = new Car();
Requires a constructor 
method to be defined :
function Car(){
 this.plate = 'My Plate';
}
Object.create()
var myCar = Object.create(Car);
Requires a prototype to be 
defined :
var Car = {
  plate: 'My Plate'
}
Two common ways to create objects are using “new” or 
“Object.create()” directives.
Define your object propertiesproperties in a constructor method 
named as the “Class” you want to create. You may add some 
default values.
function Car(){
  this.plate = '4787 BCN';
  this.manufacturer = 'Tesla';
  this.topSpeed = 80;
}
You can pass arguments to the constructor aswell.
function Car(plate, manufacturer, topSpeed){
  this.plate = plate||'4787 BCN';
  this.manufacturer = manufacturer||'Tesla';
  this.topSpeed = parseInt(topSpeed)||80;
}
new
function Car(plate, manufacturer, topSpeed){
  this.plate = plate||'4787 BCN';
  this.manufacturer = manufacturer||'Tesla';
  this.topSpeed = parseInt(topSpeed)||80;
}
var myFirstCar  = new Car();
var mySecondCar = new Car('123 SF','Ford',120);
myFirstCar.plate;
  => '4787 BCN'
mySecondCar.plate;
  => '123 SF'
new
Now define your object's methods.
function Car(plate, manufacturer, topSpeed){
  this.plate = plate||'4787 BCN';
  this.manufacturer = manufacturer||'Tesla';
  this.topSpeed = parseInt(topSpeed)||80;
  this.currentSpeed = 0;
  this.setCurrentSpeed = function(newSpeed){
   this.currentSpeed = parseInt(newSpeed);
  }
  this.accelerate = function(newSpeed){
     if(parseInt(newSpeed) <= this.topSpeed){
        this.setCurrentSpeed(newSpeed);
     }
     else{
   throw 'Your car will break.';
     }
   }
}
  
new
var myFirstCar = new Car();
myFirstCar.accelerate(15);
myFirstCar.currentSpeed;
 => 15
myFirstCar.accelerate(95);
 => Your car will break.
myFirstCar.currentSpeed;
 => 15
  
new
Let's do the same example but using 
object prototypes instead of 
constructor methods.  
Object.create()
Object prototypesprototypes are defined as a Hash :
var Car = {
  plate: '4787 BCN',
  manufacturer : 'Tesla',
  topSpeed : 80,
  currentSpeed : 0,
  setCurrentSpeed : function(newSpeed){
   this.currentSpeed = parseInt(newSpeed);
  },
  accelerate : function(newSpeed){
   if(parseInt(newSpeed) <= this.topSpeed){
      this.setCurrentSpeed(newSpeed);
   }
   else{
   throw 'Your car will break.';
   }
  }
}  
Object.create()
var myFirstCar = Object.create(Car);
myFirstCar.accelerate(15);
myFirstCar.currentSpeed;
 => 15
myFirstCar.accelerate(95);
 => Your car will break.
myFirstCar.currentSpeed;
 => 15
  
Object.create()
What if I want to modify Object 
prototype's default values at 
creation time?  
Object.create()
It requires some extra code lines 
than using a constructor method, but 
it has some cool features. 
Object.create()
var newValues = {
  plate: { 
            value: 'my Car Plate' 
          },
  manufacturer: { 
            value: 'Ford' 
        },
  topSpeed: { 
            value: 120
        },
  currentSpeed: { 
            value: 5
        }
};
var myNewCar = Object.create(Car, newValues);
myNewCar.plate;
 => 'my Car Plate'
'4787 BCN'
Car's prototype default values:
'Tesla'
80
0
Object.create()
Additional features.
Immutable properties.
This features is available because Object.create() uses 
Object.defineProperties() check :
https://developer.mozilla.org/en­US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties
Object.create()
var myNewCar = Object.create(Car, {
  plate: { 
            writable: false, 
            value: 'my Car Plate' 
          },
[...]
});
WriteableWriteable : true if and only if the valuevalue associated with the 
property may be changed with an assignment operator.
Defaults to false.
Object.create()
var myNewCar = Object.create(Car, {
  plate: { 
            writable: false, 
            value: 'my Car Plate' 
          },
[...]
});
myNewCar.plate = 'Hello';
myNewCar.plate;
  => 'my Car Plate'
Object.create()
Additional features.
Accessors
(getters and setters)
This features is available because Object.create() uses 
Object.defineProperties() check :
https://developer.mozilla.org/en­US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties
Object.create()
var myNewCar = Object.create(Car, {
  plate: { 
           writable: true, 
           value: 'my Car Plate',
           get: function(){ return this._plate.toUpperCase(); },
           set: function(value){ this._plate = value; }  
         },
[...]
});
Object.create()
var myNewCar = Object.create(Car, {
  plate: { 
           writable: true, 
           value: 'my Car Plate',
           get: function(){ return this._plate.toUpperCase(); },
           set: function(value){ this._plate = value; }  
         },
[...]
});
  => TypeError: Invalid property.  A property cannot both have 
accessors and be writable or have a value, #<Object>
Accessors and properties have to be 
defined separately.
Object.create()
var myNewCar = Object.create(Car, {
  _plate: { 
            writable: true, 
            value: 'my Car Plate' 
          },
  plate: { 
           get: function(){ return this._plate.toUpperCase(); },
           set: function(value){ this._plate = value; }  
         },
[...]
});
myNewCar.plate;
  => 'MY CAR PLATE'
Object.create()
Object Oriented 
Javascript
A pragmatic introduction
March 2015
Ibán Martínez
iban@nnset.com
www.openshopen.com

More Related Content

Viewers also liked (19)

PPT
Selection
kitturashmikittu
 
PDF
Dom 20160427 extra
terezinhaneta
 
PPT
Jarvis Pain Assessment
JoanVNAF
 
PPTX
Prototype
Wander Marcos
 
PPSX
Coach's guide to effective simulation facilitation preview
Suekennnedy
 
PPTX
Backupify CloudInno Presentation by Rob May
Datto
 
PDF
C re ate-cirma-def-060611
CSP Scarl
 
PPT
D:\Ring O 2nd Grade
guest5ac3f31
 
PPT
I4 school qrpark_promoey_piazza
CSP Scarl
 
PDF
Vượt lên nỗi đau
bita89
 
PPTX
Forum PA challenge: HALADIN's
CSP Scarl
 
PDF
Agenda digitale piemonte
CSP Scarl
 
PPT
alternatives to hysterectomy
Karl Daniel, M.D.
 
PDF
How to design for the web
Cyber-Duck
 
KEY
Buduj Wartość i Reinwestuj
GetResponse Email Marketing
 
PDF
Requisitos oo-para-projetos-oo-transicao-facil
Sandra Rocha
 
PPTX
Expeditie mont blanc
Elisabeth
 
DOCX
Handout 3 er año libertador 3er lapso
U.E.N. Libertador
 
DOC
Rajeev_CV
rajeevps
 
Selection
kitturashmikittu
 
Dom 20160427 extra
terezinhaneta
 
Jarvis Pain Assessment
JoanVNAF
 
Prototype
Wander Marcos
 
Coach's guide to effective simulation facilitation preview
Suekennnedy
 
Backupify CloudInno Presentation by Rob May
Datto
 
C re ate-cirma-def-060611
CSP Scarl
 
D:\Ring O 2nd Grade
guest5ac3f31
 
I4 school qrpark_promoey_piazza
CSP Scarl
 
Vượt lên nỗi đau
bita89
 
Forum PA challenge: HALADIN's
CSP Scarl
 
Agenda digitale piemonte
CSP Scarl
 
alternatives to hysterectomy
Karl Daniel, M.D.
 
How to design for the web
Cyber-Duck
 
Buduj Wartość i Reinwestuj
GetResponse Email Marketing
 
Requisitos oo-para-projetos-oo-transicao-facil
Sandra Rocha
 
Expeditie mont blanc
Elisabeth
 
Handout 3 er año libertador 3er lapso
U.E.N. Libertador
 
Rajeev_CV
rajeevps
 

Similar to Object-Oriented Javascript (20)

PPTX
Object oriented programming
msneha
 
PPTX
Object oriented javascript
Usman Mehmood
 
PPTX
Javascriptinobject orientedway-090512225827-phpapp02
Sopheak Sem
 
PPTX
JavaScript OOPS Implimentation
Usman Mehmood
 
PDF
Python Object Oriented Programming
Burasakorn Sabyeying
 
PDF
JavaScript Programming
Sehwan Noh
 
PDF
656981533-100-JavaScript-Interview-QnA.pdf
razaunar000
 
PPTX
Understanding-Objects-in-Javascript.pptx
MariaTrinidadTumanga
 
PDF
Object oriented approach in python programming
Srinivas Narasegouda
 
PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PPT
Chapter 1- Introduction.ppt
TigistTilahun1
 
PPTX
Prototype Object.pptx
Steins18
 
PDF
Java Programming.pdf
IthagoniShirisha
 
PDF
JavaScript Interview Questions with Answers
AK Deep Knowledge
 
PPT
Js ppt
Rakhi Thota
 
PPTX
Design patterns
F(x) Data Labs Pvt Ltd
 
DOCX
Java interview questions and answers
Krishnaov
 
PPTX
COMP111-Week-1_138439.pptx
FarooqTariq8
 
PPTX
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
AnkurSingh340457
 
PPTX
Unit No 2 Objects and Classes.pptx
DrYogeshDeshmukh1
 
Object oriented programming
msneha
 
Object oriented javascript
Usman Mehmood
 
Javascriptinobject orientedway-090512225827-phpapp02
Sopheak Sem
 
JavaScript OOPS Implimentation
Usman Mehmood
 
Python Object Oriented Programming
Burasakorn Sabyeying
 
JavaScript Programming
Sehwan Noh
 
656981533-100-JavaScript-Interview-QnA.pdf
razaunar000
 
Understanding-Objects-in-Javascript.pptx
MariaTrinidadTumanga
 
Object oriented approach in python programming
Srinivas Narasegouda
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Chapter 1- Introduction.ppt
TigistTilahun1
 
Prototype Object.pptx
Steins18
 
Java Programming.pdf
IthagoniShirisha
 
JavaScript Interview Questions with Answers
AK Deep Knowledge
 
Js ppt
Rakhi Thota
 
Design patterns
F(x) Data Labs Pvt Ltd
 
Java interview questions and answers
Krishnaov
 
COMP111-Week-1_138439.pptx
FarooqTariq8
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
AnkurSingh340457
 
Unit No 2 Objects and Classes.pptx
DrYogeshDeshmukh1
 
Ad

Recently uploaded (20)

PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Import Data Form Excel to Tally Services
Tally xperts
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Ad

Object-Oriented Javascript