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/
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.
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 :-)