SlideShare a Scribd company logo
Object-­‐‑Oriented  
Programming

  in

  JavaScript
Zander Magtipon
May 25, 2015
OOP  in  JavaScript
• Overview
• Prototype Chain
• Custom Objects
o The class
o The constructor
o The object (class instance)
o The property
o The method
o Static members
o Private and privileged members
• Inheritance
• Encapsulation
• Accessing Superclass Members
• Passing Constructor Arguments
Overview
• JavaScript is designed on a simple object-based
paradigm. An object is a collection of properties,
and a property is an association between a name
and a value. A property's value can be a function,
in which case the property is known as a method.
• One of the key differences of JavaScript from other
OOP languages is that it does not have classes.
Instead, JavaScript uses functions as classes.
• The class functionality is accomplished by object
prototypes where object inherits from another
object.
Overview
• JavaScript functions are objects, giving functions the
capacity to hold executable code and be passed
around like any other object.
• All objects in JavaScript are descended from Object
object.
• All objects inherit methods and properties from
Object.prototype.
• All object properties/methods are public.
Prototype  Chain
• A prototype chain is a finite chain of objects which is used
to implement inheritance and shared properties.
• Every object in JavaScript has an internal link to another
object called prototype. That prototype object has a
prototype of its own, and so on until an object is reached
with null as its prototype.
• __proto__ is the actual object that is used in the lookup
chain to resolve methods, etc.
• prototype is the object that is used to build __proto__ when
you create an object.
Prototype  Chain
var b = new Foo(20);
var c = new Foo(30);
Custom  Objects
• Defining a class is as easy as defining a function.
function Person() {
}
The class
Custom  Objects
• In JavaScript the function serves as the constructor
of the object.
• The constructor is used to set the object's properties
or to call methods to prepare the object for use.
function Person () {
console.log('instance created');
}
The constructor
Custom  Objects
• An instance of an object can be created by
executing the constructor function using the new
operator.
var person1 = new Person();
var person2 = new Person();
The object (class instance)
Custom  Objects
• Properties are set in the constructor of the class so
that they are created on each instance.
• The keyword this, which refers to the current object,
lets you work with properties from within the class.
The property (object attribute)
Custom  Objects
function Person(firstName) {
this.firstName = firstName;
console.log('Person instantiated');
}
var person1 = new Person('Alice');
var person2 = new Person('Bob');
// Show the firstName properties of the objects
console.log('person1 is ' + person1.firstName); // logs "person1 is Alice"
console.log('person2 is ' + person2.firstName); // logs "person2 is Bob"
The property (object attribute)
Custom  Objects
• Methods are functions that follow the same logic as
properties. Calling a method is similar to accessing a
property, but you add () at the end of the method
name, possibly with arguments.
• To define a method, assign a function to a named
property of the class's prototype property.
The method
Custom  Objects
function Person(firstName) {
this.firstName = firstName;
}
Person.prototype.sayHello = function() {
console.log("Hello, I'm " + this.firstName);
};
var person1 = new Person("Alice");
var person2 = new Person("Bob");
// call the Person sayHello method.
person1.sayHello(); // logs "Hello, I'm Alice"
person2.sayHello(); // logs "Hello, I'm Bob"
The method
Custom  Objects
• Static members (properties/methods) or class
members only exist on the class and doesn't exist on
child objects.
Static members
Custom  Objects
function Person(firstName) {
this.firstName = firstName;
}
Person.prototype.sayName = function() {
console.log("instance:", this.firstName);
};
Person.firstName = "anybody";
Person.sayName = function() {
console.log("static:", this.firstName);
};
var person1 = new Person("Alice");
person1.sayName(); // logs "instance: Alice"
Person.sayName(); // logs "static: anybody"
Static members
Custom  Objects
• Private members are made by the constructor. Local
vars and parameters of the constructor becomes
the private members.
• A privileged method is able to access the private
variables and methods, and is itself accessible to the
public methods and the outside.
Private and privileged members
Custom  Objects
function Person(firstName) {
//-- private
var _firstName = firstName;
function _getMessage() {
return "Hello my name is " + _firstName;
}
//-- privileged
this.sayHello = function() {
console.log(_getMessage());
}
}
var person1 = new Person("Alice");
person1. sayHello(); // logs "Hello my name is Alice"
Private and privileged members
Inheritance
• Inheritance is a way to create a class as a specialized
version of another class.
• JavaScript only supports single inheritance.
• When trying to access a property of an object, the
property will not only be sought on the object but on the
prototype of the object, the prototype of the prototype,
and so on until either a property with a matching name is
found or the end of the prototype chain is reached.
• When an inherited function is executed, the value of this
points to the inheriting object, not to the prototype
object where the function is an own property.
Inheritance
function Photo(name) {
this.name = name || "photo";
}
Photo.prototype.upload = function() {
console.log("Photo.upload:", this.name);
};
ProfilePhoto.prototype = Object.create(Photo.prototype);
function ProfilePhoto(name) {
Photo.call(this, name || "profile-photo");
}
var photo = new Photo();
photo.upload(); // logs "Photo.upload: photo"
var profilePhoto = new ProfilePhoto();
profilePhoto.upload(); // logs "Photo.upload: profile-photo"
Inheritance
function Photo(name) {
this.name = name || "photo";
}
Photo.prototype.upload = function() {
console.log("Photo.upload:", this.name);
};
ProfilePhoto.prototype = Object.create(Photo.prototype);
function ProfilePhoto(name) {
Photo.call(this, name || "profile-photo");
}
//-- method override
ProfilePhoto.prototype.upload = function() {
console.log("ProfilePhoto.upload:", this.name);
};
var photo = new Photo();
photo.upload(); // logs "Photo.upload: photo"
var profilePhoto = new ProfilePhoto();
profilePhoto.upload(); // logs "ProfilePhoto.upload: profile-photo"
Encapsulation
• Encapsulation includes the idea that the data of an
object should not be directly exposed.
• Instead, callers that want to achieve a given result
are coaxed into proper usage by invoking methods
(rather than accessing the data directly).
Encapsulation
function Photo(name) {
this.name = name || "photo";
}
Photo.prototype.setName = function(name) {
this.name = name;
};
Photo.prototype.getName = function() {
return this.name;
};
var photo = new Photo();
photo.setName("picture"); // sets photo name to "picture"
photo.getName(); // returns "picture"
Encapsulation
function Photo(name) {
var _name = name || "photo";
Object.defineProperty(this, "name", {
get: function() {
return _name;
},
set: function(name) {
_name = name;
}
});
}
var photo = new Photo();
photo.name = "picture"; // sets photo name to "picture"
photo.name; // returns “picture”
Accessing  Superclass  
Members
• One of the big differences between Classical
(Object-Oriented) and Prototypal inheritance is that
the former has an elegant mechanism for referring
to the parent class (usually using the super keyword).
It's often used in constructors to initialize the parent
class with the supplied input parameters. Another
common usage is to extend parent functionality in
the child class.
Accessing  Superclass  
Members
function Photo(name) {
var _name = name || "photo";
Object.defineProperty(this, "name", {
get: function() {
return _name;
}
});
}
Photo.prototype.upload = function() {
console.log("Photo.upload:", this.name);
};
Accessing  Superclass  
Members
ProfilePhoto.prototype = Object.create(Photo.prototype);
function ProfilePhoto(name) {
Photo.call(this, name || "profile-photo");
}
//-- method override
ProfilePhoto.prototype.upload = function() {
Photo.prototype.upload.call(this);
console.log(”ProfilePhoto.upload:", this.name);
};
var profilePhoto = new ProfilePhoto();
profilePhoto.upload();
// logs "Photo.upload: profile-photo"
// logs "ProfilePhoto.upload: profile-photo"
Accessing  Superclass  
Members
ProfilePhoto.prototype = Object.create(Photo.prototype);
function ProfilePhoto(name) {
Object.defineProperty(this, "parent", {
get: function() {
return Photo;
}
});
this.parent.call(this, name || "profile-photo");
}
//-- method override
ProfilePhoto.prototype.upload = function() {
this.parent.prototype.upload.call(this);
console.log(”ProfilePhoto.upload:", this.name);
};
var profilePhoto = new ProfilePhoto();
profilePhoto.upload();
// logs "Photo.upload: profile-photo"
// logs "ProfilePhoto.upload: profile-photo"
Passing  Constructor  
Arguments
function Photo(name) {
var _name = name || "photo";
Object.defineProperty(this, "name", {
get: function() {
return _name;
}
});
}
ProfilePhoto.prototype = Object.create(Photo.prototype);
function ProfilePhoto() {
Photo.apply(this, Array.prototype.slice.call(arguments));
}
var profilePhoto = new ProfilePhoto("avatar"); // sets the name to "avatar"
Questions?
Thank  You!

More Related Content

What's hot

Reactjs
ReactjsReactjs
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
NexThoughts Technologies
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
[24]안드로이드 웹뷰의 모든것
[24]안드로이드 웹뷰의 모든것[24]안드로이드 웹뷰의 모든것
[24]안드로이드 웹뷰의 모든것
NAVER Engineering
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
Anis Ahmad
 
React workshop
React workshopReact workshop
React workshop
Imran Sayed
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
Fabien Vauchelles
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
David Parsons
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
Xcat Liu
 
What is JavaScript? Edureka
What is JavaScript? EdurekaWhat is JavaScript? Edureka
What is JavaScript? Edureka
Edureka!
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
kamal kotecha
 

What's hot (20)

Reactjs
ReactjsReactjs
Reactjs
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Reactjs
Reactjs Reactjs
Reactjs
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
[24]안드로이드 웹뷰의 모든것
[24]안드로이드 웹뷰의 모든것[24]안드로이드 웹뷰의 모든것
[24]안드로이드 웹뷰의 모든것
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
React workshop
React workshopReact workshop
React workshop
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
What is JavaScript? Edureka
What is JavaScript? EdurekaWhat is JavaScript? Edureka
What is JavaScript? Edureka
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 

Viewers also liked

JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat Sheet
HDR1001
 
Javascript cheat-sheet-v1
Javascript cheat-sheet-v1Javascript cheat-sheet-v1
Javascript cheat-sheet-v1hccit
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
军 沈
 
Prototype-based Programming with JavaScript
Prototype-based Programming with JavaScriptPrototype-based Programming with JavaScript
Prototype-based Programming with JavaScript
lienhard
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
HDR1001
 
Grunt
GruntGrunt
Grunt
Dohoon Kim
 
JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
Narendra Sisodiya
 
Introduction to Object Oriented Javascript
Introduction to Object Oriented JavascriptIntroduction to Object Oriented Javascript
Introduction to Object Oriented Javascript
nodeninjas
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
CSS Sanity with Sass: The Inverted Triangle Approach
CSS Sanity with Sass: The Inverted Triangle ApproachCSS Sanity with Sass: The Inverted Triangle Approach
CSS Sanity with Sass: The Inverted Triangle Approach
Julie Kuehl
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 
SASS - CSS with Superpower
SASS - CSS with SuperpowerSASS - CSS with Superpower
SASS - CSS with Superpower
Kanchha kaji Prajapati
 
Advanced sass/compass
Advanced sass/compassAdvanced sass/compass
Advanced sass/compass
Nick Cooley
 
View, Act, and React: Shaping Business Activity with Analytics, BigData Queri...
View, Act, and React: Shaping Business Activity with Analytics, BigData Queri...View, Act, and React: Shaping Business Activity with Analytics, BigData Queri...
View, Act, and React: Shaping Business Activity with Analytics, BigData Queri...
Srinath Perera
 
Smart CSS theming with Sass and Compass
Smart CSS theming with Sass and CompassSmart CSS theming with Sass and Compass
Smart CSS theming with Sass and Compass
Mihaela
 
Syntactically awesome stylesheets (Sass)
Syntactically awesome stylesheets (Sass)Syntactically awesome stylesheets (Sass)
Syntactically awesome stylesheets (Sass)
Tahmina Khatoon
 
JavaScript OOPs
JavaScript OOPsJavaScript OOPs
JavaScript OOPs
Johnson Chou
 
Ipsec 2
Ipsec 2Ipsec 2
Ipsec 2
Sourabh Badve
 

Viewers also liked (20)

JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat Sheet
 
Javascript cheat-sheet-v1
Javascript cheat-sheet-v1Javascript cheat-sheet-v1
Javascript cheat-sheet-v1
 
Prototype
PrototypePrototype
Prototype
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Prototype-based Programming with JavaScript
Prototype-based Programming with JavaScriptPrototype-based Programming with JavaScript
Prototype-based Programming with JavaScript
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
 
Grunt
GruntGrunt
Grunt
 
JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
 
Introduction to Object Oriented Javascript
Introduction to Object Oriented JavascriptIntroduction to Object Oriented Javascript
Introduction to Object Oriented Javascript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
CSS Sanity with Sass: The Inverted Triangle Approach
CSS Sanity with Sass: The Inverted Triangle ApproachCSS Sanity with Sass: The Inverted Triangle Approach
CSS Sanity with Sass: The Inverted Triangle Approach
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
SASS - CSS with Superpower
SASS - CSS with SuperpowerSASS - CSS with Superpower
SASS - CSS with Superpower
 
Advanced sass/compass
Advanced sass/compassAdvanced sass/compass
Advanced sass/compass
 
View, Act, and React: Shaping Business Activity with Analytics, BigData Queri...
View, Act, and React: Shaping Business Activity with Analytics, BigData Queri...View, Act, and React: Shaping Business Activity with Analytics, BigData Queri...
View, Act, and React: Shaping Business Activity with Analytics, BigData Queri...
 
Smart CSS theming with Sass and Compass
Smart CSS theming with Sass and CompassSmart CSS theming with Sass and Compass
Smart CSS theming with Sass and Compass
 
Syntactically awesome stylesheets (Sass)
Syntactically awesome stylesheets (Sass)Syntactically awesome stylesheets (Sass)
Syntactically awesome stylesheets (Sass)
 
JavaScript OOPs
JavaScript OOPsJavaScript OOPs
JavaScript OOPs
 
Ipsec 2
Ipsec 2Ipsec 2
Ipsec 2
 

Similar to Object Oriented Programming in JavaScript

Chapter iii(oop)
Chapter iii(oop)Chapter iii(oop)
Chapter iii(oop)
Chhom Karath
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
LearningTech
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
deannalagason
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritancepedro.carvalho
 
oop 3.pptx
oop 3.pptxoop 3.pptx
oop 3.pptx
OsamaMuhammad18
 
Prototype & Inheritance in JavaScript
Prototype & Inheritance in JavaScriptPrototype & Inheritance in JavaScript
Prototype & Inheritance in JavaScript
Sunny Sharma
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
Usman Mehmood
 
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
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptxClasses, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
Object oriented programming in JavaScript
Object oriented programming in JavaScriptObject oriented programming in JavaScript
Object oriented programming in JavaScript
Aditya Majety
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
Toni Kolev
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 

Similar to Object Oriented Programming in JavaScript (20)

Chapter iii(oop)
Chapter iii(oop)Chapter iii(oop)
Chapter iii(oop)
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance
 
oop 3.pptx
oop 3.pptxoop 3.pptx
oop 3.pptx
 
Prototype & Inheritance in JavaScript
Prototype & Inheritance in JavaScriptPrototype & Inheritance in JavaScript
Prototype & Inheritance in JavaScript
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
Week3
Week3Week3
Week3
 
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
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptxClasses, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
 
Object oriented programming in JavaScript
Object oriented programming in JavaScriptObject oriented programming in JavaScript
Object oriented programming in JavaScript
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 

Recently uploaded

Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 

Recently uploaded (20)

Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 

Object Oriented Programming in JavaScript

  • 1. Object-­‐‑Oriented   Programming
  in
  JavaScript Zander Magtipon May 25, 2015
  • 2. OOP  in  JavaScript • Overview • Prototype Chain • Custom Objects o The class o The constructor o The object (class instance) o The property o The method o Static members o Private and privileged members • Inheritance • Encapsulation • Accessing Superclass Members • Passing Constructor Arguments
  • 3. Overview • JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name and a value. A property's value can be a function, in which case the property is known as a method. • One of the key differences of JavaScript from other OOP languages is that it does not have classes. Instead, JavaScript uses functions as classes. • The class functionality is accomplished by object prototypes where object inherits from another object.
  • 4. Overview • JavaScript functions are objects, giving functions the capacity to hold executable code and be passed around like any other object. • All objects in JavaScript are descended from Object object. • All objects inherit methods and properties from Object.prototype. • All object properties/methods are public.
  • 5. Prototype  Chain • A prototype chain is a finite chain of objects which is used to implement inheritance and shared properties. • Every object in JavaScript has an internal link to another object called prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. • __proto__ is the actual object that is used in the lookup chain to resolve methods, etc. • prototype is the object that is used to build __proto__ when you create an object.
  • 6. Prototype  Chain var b = new Foo(20); var c = new Foo(30);
  • 7. Custom  Objects • Defining a class is as easy as defining a function. function Person() { } The class
  • 8. Custom  Objects • In JavaScript the function serves as the constructor of the object. • The constructor is used to set the object's properties or to call methods to prepare the object for use. function Person () { console.log('instance created'); } The constructor
  • 9. Custom  Objects • An instance of an object can be created by executing the constructor function using the new operator. var person1 = new Person(); var person2 = new Person(); The object (class instance)
  • 10. Custom  Objects • Properties are set in the constructor of the class so that they are created on each instance. • The keyword this, which refers to the current object, lets you work with properties from within the class. The property (object attribute)
  • 11. Custom  Objects function Person(firstName) { this.firstName = firstName; console.log('Person instantiated'); } var person1 = new Person('Alice'); var person2 = new Person('Bob'); // Show the firstName properties of the objects console.log('person1 is ' + person1.firstName); // logs "person1 is Alice" console.log('person2 is ' + person2.firstName); // logs "person2 is Bob" The property (object attribute)
  • 12. Custom  Objects • Methods are functions that follow the same logic as properties. Calling a method is similar to accessing a property, but you add () at the end of the method name, possibly with arguments. • To define a method, assign a function to a named property of the class's prototype property. The method
  • 13. Custom  Objects function Person(firstName) { this.firstName = firstName; } Person.prototype.sayHello = function() { console.log("Hello, I'm " + this.firstName); }; var person1 = new Person("Alice"); var person2 = new Person("Bob"); // call the Person sayHello method. person1.sayHello(); // logs "Hello, I'm Alice" person2.sayHello(); // logs "Hello, I'm Bob" The method
  • 14. Custom  Objects • Static members (properties/methods) or class members only exist on the class and doesn't exist on child objects. Static members
  • 15. Custom  Objects function Person(firstName) { this.firstName = firstName; } Person.prototype.sayName = function() { console.log("instance:", this.firstName); }; Person.firstName = "anybody"; Person.sayName = function() { console.log("static:", this.firstName); }; var person1 = new Person("Alice"); person1.sayName(); // logs "instance: Alice" Person.sayName(); // logs "static: anybody" Static members
  • 16. Custom  Objects • Private members are made by the constructor. Local vars and parameters of the constructor becomes the private members. • A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. Private and privileged members
  • 17. Custom  Objects function Person(firstName) { //-- private var _firstName = firstName; function _getMessage() { return "Hello my name is " + _firstName; } //-- privileged this.sayHello = function() { console.log(_getMessage()); } } var person1 = new Person("Alice"); person1. sayHello(); // logs "Hello my name is Alice" Private and privileged members
  • 18. Inheritance • Inheritance is a way to create a class as a specialized version of another class. • JavaScript only supports single inheritance. • When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached. • When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.
  • 19. Inheritance function Photo(name) { this.name = name || "photo"; } Photo.prototype.upload = function() { console.log("Photo.upload:", this.name); }; ProfilePhoto.prototype = Object.create(Photo.prototype); function ProfilePhoto(name) { Photo.call(this, name || "profile-photo"); } var photo = new Photo(); photo.upload(); // logs "Photo.upload: photo" var profilePhoto = new ProfilePhoto(); profilePhoto.upload(); // logs "Photo.upload: profile-photo"
  • 20. Inheritance function Photo(name) { this.name = name || "photo"; } Photo.prototype.upload = function() { console.log("Photo.upload:", this.name); }; ProfilePhoto.prototype = Object.create(Photo.prototype); function ProfilePhoto(name) { Photo.call(this, name || "profile-photo"); } //-- method override ProfilePhoto.prototype.upload = function() { console.log("ProfilePhoto.upload:", this.name); }; var photo = new Photo(); photo.upload(); // logs "Photo.upload: photo" var profilePhoto = new ProfilePhoto(); profilePhoto.upload(); // logs "ProfilePhoto.upload: profile-photo"
  • 21. Encapsulation • Encapsulation includes the idea that the data of an object should not be directly exposed. • Instead, callers that want to achieve a given result are coaxed into proper usage by invoking methods (rather than accessing the data directly).
  • 22. Encapsulation function Photo(name) { this.name = name || "photo"; } Photo.prototype.setName = function(name) { this.name = name; }; Photo.prototype.getName = function() { return this.name; }; var photo = new Photo(); photo.setName("picture"); // sets photo name to "picture" photo.getName(); // returns "picture"
  • 23. Encapsulation function Photo(name) { var _name = name || "photo"; Object.defineProperty(this, "name", { get: function() { return _name; }, set: function(name) { _name = name; } }); } var photo = new Photo(); photo.name = "picture"; // sets photo name to "picture" photo.name; // returns “picture”
  • 24. Accessing  Superclass   Members • One of the big differences between Classical (Object-Oriented) and Prototypal inheritance is that the former has an elegant mechanism for referring to the parent class (usually using the super keyword). It's often used in constructors to initialize the parent class with the supplied input parameters. Another common usage is to extend parent functionality in the child class.
  • 25. Accessing  Superclass   Members function Photo(name) { var _name = name || "photo"; Object.defineProperty(this, "name", { get: function() { return _name; } }); } Photo.prototype.upload = function() { console.log("Photo.upload:", this.name); };
  • 26. Accessing  Superclass   Members ProfilePhoto.prototype = Object.create(Photo.prototype); function ProfilePhoto(name) { Photo.call(this, name || "profile-photo"); } //-- method override ProfilePhoto.prototype.upload = function() { Photo.prototype.upload.call(this); console.log(”ProfilePhoto.upload:", this.name); }; var profilePhoto = new ProfilePhoto(); profilePhoto.upload(); // logs "Photo.upload: profile-photo" // logs "ProfilePhoto.upload: profile-photo"
  • 27. Accessing  Superclass   Members ProfilePhoto.prototype = Object.create(Photo.prototype); function ProfilePhoto(name) { Object.defineProperty(this, "parent", { get: function() { return Photo; } }); this.parent.call(this, name || "profile-photo"); } //-- method override ProfilePhoto.prototype.upload = function() { this.parent.prototype.upload.call(this); console.log(”ProfilePhoto.upload:", this.name); }; var profilePhoto = new ProfilePhoto(); profilePhoto.upload(); // logs "Photo.upload: profile-photo" // logs "ProfilePhoto.upload: profile-photo"
  • 28. Passing  Constructor   Arguments function Photo(name) { var _name = name || "photo"; Object.defineProperty(this, "name", { get: function() { return _name; } }); } ProfilePhoto.prototype = Object.create(Photo.prototype); function ProfilePhoto() { Photo.apply(this, Array.prototype.slice.call(arguments)); } var profilePhoto = new ProfilePhoto("avatar"); // sets the name to "avatar"