SlideShare ist ein Scribd-Unternehmen logo
1 von 35
OBJECT ORIENTED JAVASCRIPT
Getting Started
OBJECT ORIENTED JAVASCRIPT
The purpose of this presentation is to
elaborate how to use object oriented
approach when codding in JavaScript
Created By :

Usman Mehmood
Senior software Engineer
Systems Limited
97-Aziz Avenue Canal Bank, Gulberg V, Lahore, Pakistan
Office: +92-42- 3577 5582 - 85 EXT: 245
VOIP: + 1 732 994 6492 - 94 EXT: 245 Fax: +92 423 587 7238
Email: usman.tufail@systemsltd.com
Website: http://www.systemsltd.com
OBJECT-ORIENTED PROGRAMMING






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. Today, many popular programming
languages (such as Java, JavaScript, C#, C++, Python, PHP, Ruby and
Objective-C) support object-oriented programming (OOP).
Object-oriented programming may be seen as the design of software
using a collection of cooperating objects, as opposed to a traditional view
in which a program may be seen as a collection of functions, or simply as
a list of instructions to the computer. In OOP, each object is capable of
receiving messages, processing data, and sending messages to other
objects. Each object can be viewed as an independent little machine with
a distinct role or responsibility.
Object-oriented programming is intended to promote greater flexibility
and maintainability in programming, and is widely popular in large-scale
software engineering. By virtue of its strong emphasis on modularity,
object oriented code is intended to be simpler to develop and easier to
understand later on, lending itself to more direct analysis, coding, and
understanding of complex situations and procedures than less modular
programming methods.
TERMINOLOGY













Class: Defines the characteristics of the
Object. An Instance of a Class.
Property An Object characteristic, such as color.
Method: An Object capability, such as walk.
Constructor: A method called at the moment of instantiation.
Inheritance: A Class can inherit characteristics from another
Class.
Encapsulation: A Class defines only the characteristics of the
Object, a method defines only how the method executes.
Abstraction: The conjunction of complex inheritance,
methods, properties of an Object must be able to simulate a
reality model.
Polymorphism
Different Classes might define the same method or property.
PROTOTYPE-BASED PROGRAMMING




Prototype-based programming is a style of objectoriented programming in which classes are not present,
and behavior reuse (known as inheritance in classbased languages) is accomplished through a process of
decorating existing objects which serve as prototypes.
This model is also known as class-less, prototypeoriented, or instance-based programming.
The original (and most canonical) example of a
prototype-based language is the programming language
Self developed by David Ungar and Randall Smith.
However, the class-less programming style has recently
grown increasingly popular, and has been adopted for
programming languages such as JavaScript, Cecil,
NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when
using the Viewer framework to manipulate Morphic
components), and several others
ENUMERATING ALL PROPERTIES









Enumerating all properties of an object
Starting with ECMAScript 5, there are three native ways
to list/traverse object properties:
for...in loops
This method traverses all enumerable properties of an
object and its prototype chain
Object.keys(o)
This method returns an array with all the own (not in the
prototype chain) enumerable properties' names ("keys")
of an object o.
Object.getOwnPropertyNames(o)
This method returns an array containing all own
properties' names (enumerable or not) of an object o.




In ECMAScript 5, there is no native way to list all
properties of an object. However, this can be
achieved with the following function:
CORE OBJECTS


JavaScript has several objects included in its core;
for example, there are objects like Math, Object,
Array, and String. The example below shows how to
use the Math object to get a random number by
using its random() method.



you can look here for all core objects
NOTE


Every object in JavaScript is an instance of the
object Object and therefore inherits all its properties
and methods.
CUSTOM OBJECTS
The Class:
JavaScript is a prototype-based language which contains no class statement,
such as is found in C++ or Java. This is sometimes confusing for programmers
accustomed to languages with a class statement. Instead, JavaScript uses
functions as classes. Defining a class is as easy as defining a function. In the
example below we define a new class called Person.
THE OBJECT (CLASS INSTANCE)
To create a new instance of an object obj we use the
statement new obj, assigning the result (which is of type obj) to a
variable to access it later. In the example below we define a
class named Person and we create two instances
(person1 and person2).

Please also see Object.create for a new
and alternative instantiation method.
THE CONSTRUCTOR


The constructor is called at the moment of instantiation (the moment when the
object instance is created). The constructor is a method of the class. In
JavaScript, the function serves as the constructor of the object; therefore,
there is no need to explicitly define a constructor method. Every action
declared in the class gets executed at the time of instantiation. The
constructor is used to set the object's properties or to call methods to prepare
the object for use. Adding class methods and their definitions occurs using a
different syntax described later in this article.In the example below, the
constructor of the class Person displays an alert when a Person is
instantiated.
THE PROPERTY (OBJECT ATTRIBUTE)




Properties are variables contained in the class; every instance
of the object has those properties. Properties should be set in
the prototype property of the class (function) so that
inheritance works correctly.
Working with properties from within the class is done by the
keyword this, which refers to the current object. Accessing
(reading or writing) a property outside of the class is done with
the syntax: InstanceName.Property; this is the same syntax
used by C++, Java, and a number of other languages. (Inside
the class the syntax this.Property is used to get or set the
property's value.)
IN THE EXAMPLE BELOW WE DEFINE
THE GENDER PROPERTY FOR THE PERSON CLASS AND WE
DEFINE IT AT INSTANTIATION
THE METHODS


Methods follow the same logic as properties; the
difference is that they are functions and they are
defined as functions. 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 name
that the function is assigned to is the name that the
method is called by on the object.
IN THE EXAMPLE BELOW WE DEFINE AND USE THE
METHOD SAYHELLO() FOR THE PERSON CLASS.
IN JAVASCRIPT METHODS ARE REGULAR FUNCTION OBJECTS THAT ARE BOUND TO A
CLASS/OBJECT AS A PROPERTY WHICH MEANS THEY CAN BE INVOKED "OUT OF THE
CONTEXT". CONSIDER THE FOLLOWING EXAMPLE CODE:

This example demonstrates many concepts at once. It shows that there are no "per-object
methods" in JavaScript since all references to the method point to the exact same function, the
one we have defined in the first place on the prototype. JavaScript "binds" the current "object
context" to the special "this" variable when a function is invoked as a method(or property to be
exact) of an object. This is equal to calling the function object's "call" method as follows:
INHERITANCE


Inheritance is a way to create a class as a
specialized version of one or more classes
(JavaScript only supports single class inheritance).
The specialized class is commonly called the child,
and the other class is commonly called the parent.
In JavaScript you do this by assigning an instance
of the parent class to the child class, and then
specializing it. In modern browsers you can also
use Object.create to implement inheritance.
IMPORTANT


JavaScript does not detect the child
class prototype.constructor see Core JavaScript 1.5
Reference:Global
Objects:Object:prototype property, so we must state
that manually.
IN THE EXAMPLE BELOW, WE DEFINE THE CLASS STUDENT AS A CHILD
CLASS OF PERSON. THEN WE REDEFINE THE SAYHELLO() METHOD
AND ADD THESAYGOODBYE() METHOD.
Click here to open code
ENCAPSULATION


In the previous example, Student does not need to
know how the Person class's walk() method is
implemented, but still can use that method;
theStudent class doesn't need to explicitly define
that method unless we want to change it. This is
called encapsulation, by which every class inherits
the methods of its parent and only needs to define
things it wishes to change.
Example
ABSTRACTION
Abstraction is a mechanism that permits modeling
the current part of the working problem. This can be
achieved by inheritance (specialization), or
composition. JavaScript achieves specialization by
inheritance, and composition by letting instances of
classes be the values of attributes of other objects.
 The JavaScript Function class inherits from the
Object class (this demonstrates specialization of
the model). and the Function. prototype property is
an instance of Object (this demonstrates
composition) Abstraction example

CREATING OBJECTS


http://jsfiddle.net/mehmoodusman786/JLQFY/
INNER FUNCTIONS
JavaScript function declarations are allowed inside
other functions. We've seen this once before, with
an earlier makePerson() function. An important
detail of nested functions in JavaScript is that they
can access variables in their parent function's
scope:
 http://jsfiddle.net/mehmoodusman786/GFQha/1/

CLOSURES
function makeAdder(a)
{
 return function(b) {
 return a + b; }
 }
 x = makeAdder(5);
 y = makeAdder(20);
 x(6) ?
 y(7) ?

CLOSURES


What's happening here is pretty much the same as
was happening with the inner functions earlier on: a
function defined inside another function has access
to the outer function's variables. The only difference
here is that the outer function has returned, and
hence common sense would seem to dictate that its
local variables no longer exist. But they do still exist
— otherwise the adder functions would be unable
to work. What's more, there are two different
"copies" ofmakeAdder's local variables — one in
which a is 5 and one in which a is 20. So the result
of those function calls is as follows:
CLOSURES


Whenever JavaScript executes a function, a 'scope'
object is created to hold the local variables created
within that function. It is initialised with any
variables passed in as function parameters. This is
similar to the global object that all global variables
and functions live in, but with a couple of important
differences: firstly, a brand new scope object is
created every time a function starts executing, and
secondly, unlike the global object (which in
browsers is accessible as window) these scope
objects cannot be directly accessed from your
JavaScript code. There is no mechanism for
iterating over the properties of the current scope
object for example.
CLOSURES


x(6) // returns 11 y(7) // returns 27
CLOSURES







So when makeAdder is called, a scope object is created with
one property: a, which is the argument passed to
the makeAdder function. makeAdder then returns a newly
created function. Normally JavaScript's garbage collector
would clean up the scope object created for makeAdder at this
point, but the returned function maintains a reference back to
that scope object. As a result, the scope object will not be
garbage collected until there are no more references to the
function object that makeAdder returned.
Scope objects form a chain called the scope chain, similar to
the prototype chain used by JavaScript's object system.
A closure is the combination of a function and the scope
object in which it was created.
Closures let you save state — as such, they can often be
used in place of objects.
MEMORY LEAKS








An unfortunate side effect of closures is that they make it
trivially easy to leak memory in Internet Explorer. JavaScript is
a garbage collected language — objects are allocated
memory upon their creation and that memory is reclaimed by
the browser when no references to an object remain. Objects
provided by the host environment are handled by that
environment.
Browser hosts need to manage a large number of objects
representing the HTML page being presented — the objects
of the DOM. It is up to the browser to manage the allocation
and recovery of these.
Internet Explorer uses its own garbage collection scheme for
this, separate from the mechanism used by JavaScript. It is
the interaction between the two that can cause memory leaks.
A memory leak in IE occurs any time a circular reference is
formed between a JavaScript object and a native object.
Consider the following:
MEMORY LEAKS
function leakMemory() { var el =
document.getElementById('el'); var o = { 'el': el };
el.o = o; }
 The circular reference formed above creates a
memory leak; IE will not free the memory used
by el and o until the browser is completely
restarted.

MEMORY LEAKS








Closures make it easy to create a memory leak without
meaning to. Consider this:
function addHandler() { var el =
document.getElementById('el'); el.onclick = function() {
this.style.backgroundColor = 'red'; } }
The above code sets up the element to turn red when it
is clicked. It also creates a memory leak. Why? Because
the reference to el is inadvertently caught in the closure
created for the anonymous inner function. This creates a
circular reference between a JavaScript object (the
function) and a native object (el).
There are a number of workarounds for this problem.
The simplest is not to use the el variable:
MEMORY LEAKS
There are a number of workarounds for this
problem. The simplest is not to use the el variable:
 function addHandler(){
document.getElementById('el').onclick = function(){
this.style.backgroundColor = 'red'; } }




Surprisingly, one trick for breaking circular
references introduced by a closure is to add
another closure:
MEMORY LEAKS





function addHandler() { var clickHandler = function() {
this.style.backgroundColor = 'red'; }; (function() { var el =
document.getElementById('el'); el.onclick =
clickHandler; })(); }
The inner function is executed straight away, and hides
its contents from the closure created with clickHandler.
Another good trick for avoiding closures is breaking
circular references during the window.onunload event.
Many event libraries will do this for you. Note that doing
so disables bfcache in Firefox 1.5, so you should not
register an unload listener in Firefox, unless you have
other reasons to do so.
A JAVASCRIPT EXAMPLE USING
OBJECT.DEFINEPROPERTY
A JavaScript example using Object.defineProperty
 var Person = function() { };
Object.defineProperty(Person.prototype, "name", {
get: function() { return this._name ? this._name :
"John Doe"; } }); var someone = new Person();
console.log( someone.name ); Please note that in
the example above, I add the name property on
the prototype object and not directly on the Person
object (to increase performance).
 In my opinion this is really simple and very elegant.
You decrease boilerplate code throughout your
whole solution, but still achieve data data
encapsulation - and that's very cool :-)


Weitere ähnliche Inhalte

Was ist angesagt?

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 

Was ist angesagt? (20)

OOPS in Java
OOPS in JavaOOPS in Java
OOPS in Java
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Inheritance Mixins & Traits
Inheritance Mixins & TraitsInheritance Mixins & Traits
Inheritance Mixins & Traits
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael Magana
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
 
Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 

Ähnlich wie Object oriented javascript

FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
AnkurSingh340457
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02
Sopheak Sem
 
Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
dannygriff1
 

Ähnlich wie Object oriented javascript (20)

FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
 
python.pptx
python.pptxpython.pptx
python.pptx
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
Object oriented programming in JavaScript
Object oriented programming in JavaScriptObject oriented programming in JavaScript
Object oriented programming in JavaScript
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Only oop
Only oopOnly oop
Only oop
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02Javascriptinobject orientedway-090512225827-phpapp02
Javascriptinobject orientedway-090512225827-phpapp02
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Prototype Object.pptx
Prototype Object.pptxPrototype Object.pptx
Prototype Object.pptx
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
Oops
OopsOops
Oops
 
DeclaringConstructir.pptx
DeclaringConstructir.pptxDeclaringConstructir.pptx
DeclaringConstructir.pptx
 
Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptx
 
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptxJAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S-complete-chrome.pptx
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorial
 

Kürzlich hochgeladen

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Object oriented javascript

  • 2. OBJECT ORIENTED JAVASCRIPT The purpose of this presentation is to elaborate how to use object oriented approach when codding in JavaScript Created By : Usman Mehmood Senior software Engineer Systems Limited 97-Aziz Avenue Canal Bank, Gulberg V, Lahore, Pakistan Office: +92-42- 3577 5582 - 85 EXT: 245 VOIP: + 1 732 994 6492 - 94 EXT: 245 Fax: +92 423 587 7238 Email: usman.tufail@systemsltd.com Website: http://www.systemsltd.com
  • 3. OBJECT-ORIENTED PROGRAMMING    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. Today, many popular programming languages (such as Java, JavaScript, C#, C++, Python, PHP, Ruby and Objective-C) support object-oriented programming (OOP). Object-oriented programming may be seen as the design of software using a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a collection of functions, or simply as a list of instructions to the computer. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent little machine with a distinct role or responsibility. Object-oriented programming is intended to promote greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. By virtue of its strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to understand later on, lending itself to more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods.
  • 4. TERMINOLOGY           Class: Defines the characteristics of the Object. An Instance of a Class. Property An Object characteristic, such as color. Method: An Object capability, such as walk. Constructor: A method called at the moment of instantiation. Inheritance: A Class can inherit characteristics from another Class. Encapsulation: A Class defines only the characteristics of the Object, a method defines only how the method executes. Abstraction: The conjunction of complex inheritance, methods, properties of an Object must be able to simulate a reality model. Polymorphism Different Classes might define the same method or property.
  • 5. PROTOTYPE-BASED PROGRAMMING   Prototype-based programming is a style of objectoriented programming in which classes are not present, and behavior reuse (known as inheritance in classbased languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototypeoriented, or instance-based programming. The original (and most canonical) example of a prototype-based language is the programming language Self developed by David Ungar and Randall Smith. However, the class-less programming style has recently grown increasingly popular, and has been adopted for programming languages such as JavaScript, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when using the Viewer framework to manipulate Morphic components), and several others
  • 6. ENUMERATING ALL PROPERTIES      Enumerating all properties of an object Starting with ECMAScript 5, there are three native ways to list/traverse object properties: for...in loops This method traverses all enumerable properties of an object and its prototype chain Object.keys(o) This method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o. Object.getOwnPropertyNames(o) This method returns an array containing all own properties' names (enumerable or not) of an object o.
  • 7.   In ECMAScript 5, there is no native way to list all properties of an object. However, this can be achieved with the following function:
  • 8. CORE OBJECTS  JavaScript has several objects included in its core; for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.  you can look here for all core objects
  • 9. NOTE  Every object in JavaScript is an instance of the object Object and therefore inherits all its properties and methods.
  • 10. CUSTOM OBJECTS The Class: JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is sometimes confusing for programmers accustomed to languages with a class statement. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person.
  • 11. THE OBJECT (CLASS INSTANCE) To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later. In the example below we define a class named Person and we create two instances (person1 and person2). Please also see Object.create for a new and alternative instantiation method.
  • 12. THE CONSTRUCTOR  The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript, the function serves as the constructor of the object; therefore, there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation. The constructor is used to set the object's properties or to call methods to prepare the object for use. Adding class methods and their definitions occurs using a different syntax described later in this article.In the example below, the constructor of the class Person displays an alert when a Person is instantiated.
  • 13. THE PROPERTY (OBJECT ATTRIBUTE)   Properties are variables contained in the class; every instance of the object has those properties. Properties should be set in the prototype property of the class (function) so that inheritance works correctly. Working with properties from within the class is done by the keyword this, which refers to the current object. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property; this is the same syntax used by C++, Java, and a number of other languages. (Inside the class the syntax this.Property is used to get or set the property's value.)
  • 14. IN THE EXAMPLE BELOW WE DEFINE THE GENDER PROPERTY FOR THE PERSON CLASS AND WE DEFINE IT AT INSTANTIATION
  • 15. THE METHODS  Methods follow the same logic as properties; the difference is that they are functions and they are defined as functions. 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 name that the function is assigned to is the name that the method is called by on the object.
  • 16. IN THE EXAMPLE BELOW WE DEFINE AND USE THE METHOD SAYHELLO() FOR THE PERSON CLASS.
  • 17. IN JAVASCRIPT METHODS ARE REGULAR FUNCTION OBJECTS THAT ARE BOUND TO A CLASS/OBJECT AS A PROPERTY WHICH MEANS THEY CAN BE INVOKED "OUT OF THE CONTEXT". CONSIDER THE FOLLOWING EXAMPLE CODE: This example demonstrates many concepts at once. It shows that there are no "per-object methods" in JavaScript since all references to the method point to the exact same function, the one we have defined in the first place on the prototype. JavaScript "binds" the current "object context" to the special "this" variable when a function is invoked as a method(or property to be exact) of an object. This is equal to calling the function object's "call" method as follows:
  • 18. INHERITANCE  Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single class inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.
  • 19. IMPORTANT  JavaScript does not detect the child class prototype.constructor see Core JavaScript 1.5 Reference:Global Objects:Object:prototype property, so we must state that manually.
  • 20. IN THE EXAMPLE BELOW, WE DEFINE THE CLASS STUDENT AS A CHILD CLASS OF PERSON. THEN WE REDEFINE THE SAYHELLO() METHOD AND ADD THESAYGOODBYE() METHOD. Click here to open code
  • 21. ENCAPSULATION  In the previous example, Student does not need to know how the Person class's walk() method is implemented, but still can use that method; theStudent class doesn't need to explicitly define that method unless we want to change it. This is called encapsulation, by which every class inherits the methods of its parent and only needs to define things it wishes to change. Example
  • 22. ABSTRACTION Abstraction is a mechanism that permits modeling the current part of the working problem. This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects.  The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model). and the Function. prototype property is an instance of Object (this demonstrates composition) Abstraction example 
  • 24. INNER FUNCTIONS JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier makePerson() function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:  http://jsfiddle.net/mehmoodusman786/GFQha/1/ 
  • 25. CLOSURES function makeAdder(a) {  return function(b) {  return a + b; }  }  x = makeAdder(5);  y = makeAdder(20);  x(6) ?  y(7) ? 
  • 26. CLOSURES  What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they do still exist — otherwise the adder functions would be unable to work. What's more, there are two different "copies" ofmakeAdder's local variables — one in which a is 5 and one in which a is 20. So the result of those function calls is as follows:
  • 27. CLOSURES  Whenever JavaScript executes a function, a 'scope' object is created to hold the local variables created within that function. It is initialised with any variables passed in as function parameters. This is similar to the global object that all global variables and functions live in, but with a couple of important differences: firstly, a brand new scope object is created every time a function starts executing, and secondly, unlike the global object (which in browsers is accessible as window) these scope objects cannot be directly accessed from your JavaScript code. There is no mechanism for iterating over the properties of the current scope object for example.
  • 28. CLOSURES  x(6) // returns 11 y(7) // returns 27
  • 29. CLOSURES     So when makeAdder is called, a scope object is created with one property: a, which is the argument passed to the makeAdder function. makeAdder then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope object created for makeAdder at this point, but the returned function maintains a reference back to that scope object. As a result, the scope object will not be garbage collected until there are no more references to the function object that makeAdder returned. Scope objects form a chain called the scope chain, similar to the prototype chain used by JavaScript's object system. A closure is the combination of a function and the scope object in which it was created. Closures let you save state — as such, they can often be used in place of objects.
  • 30. MEMORY LEAKS     An unfortunate side effect of closures is that they make it trivially easy to leak memory in Internet Explorer. JavaScript is a garbage collected language — objects are allocated memory upon their creation and that memory is reclaimed by the browser when no references to an object remain. Objects provided by the host environment are handled by that environment. Browser hosts need to manage a large number of objects representing the HTML page being presented — the objects of the DOM. It is up to the browser to manage the allocation and recovery of these. Internet Explorer uses its own garbage collection scheme for this, separate from the mechanism used by JavaScript. It is the interaction between the two that can cause memory leaks. A memory leak in IE occurs any time a circular reference is formed between a JavaScript object and a native object. Consider the following:
  • 31. MEMORY LEAKS function leakMemory() { var el = document.getElementById('el'); var o = { 'el': el }; el.o = o; }  The circular reference formed above creates a memory leak; IE will not free the memory used by el and o until the browser is completely restarted. 
  • 32. MEMORY LEAKS     Closures make it easy to create a memory leak without meaning to. Consider this: function addHandler() { var el = document.getElementById('el'); el.onclick = function() { this.style.backgroundColor = 'red'; } } The above code sets up the element to turn red when it is clicked. It also creates a memory leak. Why? Because the reference to el is inadvertently caught in the closure created for the anonymous inner function. This creates a circular reference between a JavaScript object (the function) and a native object (el). There are a number of workarounds for this problem. The simplest is not to use the el variable:
  • 33. MEMORY LEAKS There are a number of workarounds for this problem. The simplest is not to use the el variable:  function addHandler(){ document.getElementById('el').onclick = function(){ this.style.backgroundColor = 'red'; } }   Surprisingly, one trick for breaking circular references introduced by a closure is to add another closure:
  • 34. MEMORY LEAKS    function addHandler() { var clickHandler = function() { this.style.backgroundColor = 'red'; }; (function() { var el = document.getElementById('el'); el.onclick = clickHandler; })(); } The inner function is executed straight away, and hides its contents from the closure created with clickHandler. Another good trick for avoiding closures is breaking circular references during the window.onunload event. Many event libraries will do this for you. Note that doing so disables bfcache in Firefox 1.5, so you should not register an unload listener in Firefox, unless you have other reasons to do so.
  • 35. A JAVASCRIPT EXAMPLE USING OBJECT.DEFINEPROPERTY A JavaScript example using Object.defineProperty  var Person = function() { }; Object.defineProperty(Person.prototype, "name", { get: function() { return this._name ? this._name : "John Doe"; } }); var someone = new Person(); console.log( someone.name ); Please note that in the example above, I add the name property on the prototype object and not directly on the Person object (to increase performance).  In my opinion this is really simple and very elegant. You decrease boilerplate code throughout your whole solution, but still achieve data data encapsulation - and that's very cool :-) 