SlideShare a Scribd company logo
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 :-)


More Related Content

PPTX
JavaScript OOPS Implimentation
Usman Mehmood
 
PPTX
Object Oriented Javascript part2
Usman Mehmood
 
PPTX
Ruby object model
Chamnap Chhorn
 
PPT
Oops Concept Java
Kamlesh Singh
 
PPT
Oop java
Minal Maniar
 
PPTX
OOPs in Java
Ranjith Sekar
 
PPTX
Java basics
Shivanshu Purwar
 
JavaScript OOPS Implimentation
Usman Mehmood
 
Object Oriented Javascript part2
Usman Mehmood
 
Ruby object model
Chamnap Chhorn
 
Oops Concept Java
Kamlesh Singh
 
Oop java
Minal Maniar
 
OOPs in Java
Ranjith Sekar
 
Java basics
Shivanshu Purwar
 

What's hot (20)

PPTX
OOPS in Java
Zeeshan Khan
 
PPT
Oops in Java
malathip12
 
PPT
Java oops and fundamentals
javaease
 
ODP
Beginners Guide to Object Orientation in PHP
Rick Ogden
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPTX
Object oriented programming in java
Elizabeth alexander
 
PPT
Oops concepts in php
CPD INDIA
 
PPTX
Inheritance Mixins & Traits
Maximiliano Fierro
 
PDF
The Ruby Object Model by Rafael Magana
Rafael Magana
 
PDF
Java Programming Paradigms Chapter 1
Sakthi Durai
 
PPTX
Php oop presentation
Mutinda Boniface
 
PPTX
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
PPTX
object oriented programing lecture 1
Geophery sanga
 
PPTX
Object oreinted php | OOPs
Ravi Bhadauria
 
PDF
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
PPT
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
PPT
11 Using classes and objects
maznabili
 
PDF
Object oriented approach in python programming
Srinivas Narasegouda
 
PPT
Java: Objects and Object References
Tareq Hasan
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
OOPS in Java
Zeeshan Khan
 
Oops in Java
malathip12
 
Java oops and fundamentals
javaease
 
Beginners Guide to Object Orientation in PHP
Rick Ogden
 
Classes, objects in JAVA
Abhilash Nair
 
Object oriented programming in java
Elizabeth alexander
 
Oops concepts in php
CPD INDIA
 
Inheritance Mixins & Traits
Maximiliano Fierro
 
The Ruby Object Model by Rafael Magana
Rafael Magana
 
Java Programming Paradigms Chapter 1
Sakthi Durai
 
Php oop presentation
Mutinda Boniface
 
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
object oriented programing lecture 1
Geophery sanga
 
Object oreinted php | OOPs
Ravi Bhadauria
 
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
11 Using classes and objects
maznabili
 
Object oriented approach in python programming
Srinivas Narasegouda
 
Java: Objects and Object References
Tareq Hasan
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Ad

Similar to Object oriented javascript (20)

PPTX
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
AnkurSingh340457
 
PPTX
python.pptx
Dhanushrajucm
 
PDF
JAVA-PPT'S.pdf
AnmolVerma363503
 
PPTX
Object oriented programming in JavaScript
Aditya Majety
 
PPTX
Android Training (Java Review)
Khaled Anaqwa
 
PPTX
Only oop
anitarooge
 
DOCX
Question and answer Programming
Inocentshuja Ahmad
 
PPTX
Javascriptinobject orientedway-090512225827-phpapp02
Sopheak Sem
 
ODP
(An Extended) Beginners Guide to Object Orientation in PHP
Rick Ogden
 
PPTX
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
PPSX
Oop features java presentationshow
ilias ahmed
 
PPTX
Object oriented programming
Amit Soni (CTFL)
 
PPTX
Prototype Object.pptx
Steins18
 
PPTX
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Ayes Chinmay
 
PPTX
DeclaringConstructir.pptx
SinbadMagi
 
PPTX
Is2215 lecture2 student(2)
dannygriff1
 
PPTX
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
PPTX
JAVA-PPT'S.pptx
RaazIndia
 
PPT
packages and interfaces
madhavi patil
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
AnkurSingh340457
 
python.pptx
Dhanushrajucm
 
JAVA-PPT'S.pdf
AnmolVerma363503
 
Object oriented programming in JavaScript
Aditya Majety
 
Android Training (Java Review)
Khaled Anaqwa
 
Only oop
anitarooge
 
Question and answer Programming
Inocentshuja Ahmad
 
Javascriptinobject orientedway-090512225827-phpapp02
Sopheak Sem
 
(An Extended) Beginners Guide to Object Orientation in PHP
Rick Ogden
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
Oop features java presentationshow
ilias ahmed
 
Object oriented programming
Amit Soni (CTFL)
 
Prototype Object.pptx
Steins18
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Ayes Chinmay
 
DeclaringConstructir.pptx
SinbadMagi
 
Is2215 lecture2 student(2)
dannygriff1
 
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
JAVA-PPT'S.pptx
RaazIndia
 
packages and interfaces
madhavi patil
 
Ad

Recently uploaded (20)

PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 

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: [email protected] 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 :-) 