Book Excerpt: Object-Oriented JavaScript
|
|
This excerpt from
Microsoft AJAX Library Essentials by Cristian Darie, Bogdan
Brinzarea, is printed with permission from Packt
Publishing, Copyright 2007.
Concepts of Object-Oriented Programming
Most ASP.NET developers are familiar with the fundamental OOP principles because
this knowledge is important when developing for the .NET development.
Similarly, to develop client-side code using the Microsoft AJAX Library, you
need to be familiar with JavaScript's OOP features. Although not particularly
diffi cult, understanding these features can be a bit challenging at fi rst,
because JavaScript's OOP model is different than that of languages such as C#,
VB.NET, C++, or Java.
JavaScript is an object-based language. Just as in C#, you can create objects,
call their methods, pass them as parameters, and so on. You could see this
clearly when working with the DOM, where you manipulated the HTML document
through the methods and properties of the implicit document object. However,
JavaScript isn't generally considered a fully object-oriented language because
it lacks support for some features that you'd fi nd in "real" OOP languages, or
simply implements them differently.
|
|
Your most important goal for this chapter is to understand how to work with
JavaScript objects. As an ASP.NET developer, we assume that you already know
how OOP works with .NET languages, although advanced knowledge isn't necessary.
A tutorial written by Cristian Darie on OOP development with C# can be
downloaded in PDF format at http://www.cristiandarie.ro/downloads/.
To ensure we start off from the same square, in the following couple of pages
we'll review the essential OOP concepts as they apply in C# and other
languages—objects, classes, encapsulation, inheritance, and polymorphism. Then
we'll continue by "porting" this knowledge into the JavaScript realm.
Objects and Classes
What does "object-oriented programming" mean anyway? Basically, as the name
suggests, OOP puts objects at the centre of the programming model. The object
is probably the most important concept in the world of OOP—a self-contained
entity that has state and behavior, just like a real-world object. Each object
is an instance of a class (also called type), which defi nes the behavior that
is shared by all its objects.
We often use objects and classes in our programs to represent real-world
objects, and types (classes) of objects. For example, we can have classes like
Car, Customer, Document, or Person, and objects such as myCar, johnsCar, or
davesCar.
The concept is intuitive: the class represents the blueprint, or model, and
objects are particular instances of that model. For example, all objects of
type Car will have the same behavior—for example, the ability to change gear.
However, each individual Car object may be in a different gear at any
particular time—each object has its particular state. In programming, an
object's state is described by its fi elds and properties, and its behavior is
defi ned by its methods and events.
You've already worked with objects in the previous chapter. First, you've worked
with the built-in document object. This is a default DOM object that represents
the current page, and it allows you to alter the state of the page. However,
you also learned how to create your own objects, when you created the xmlHttp
object. In that case, xmlHttp is an object of the XMLHttpRequest class. You
could create more XMLHttpRequest objects, and all of them would have the same
abilities (behavior), such as the ability to contact remote servers as you
learned earlier, but each would have a different state. For example, each of
them may be contacting a different server.
In OOP's world everything revolves around objects and classes, and OOP languages
usually offer three specifi c features for manipulating them—encapsulation,
inheritance, and polymorphism.
Encapsulation
Encapsulation is a concept that allows the use of an object without having to
know its internal implementation in detail. The interaction with an object is
done only via its public interface, which contains public members and methods.
We can say that encapsulation allows an object to be treated as a "black box",
separating the implementation from its interface. Think of the objects you've
worked with so far: document, a DOM object, and xmlHttp, an XMLHttpRequest
object. You certainly don't know how these objects do their work internally!
All you have to know is the features you can use.
The "features you can use" of a class form the public interface of a class,
which is the sum of all its public members. The public members are those
members that are visible and can be used by external classes. For example, the
innerHTML property of a DOM object (such as the default document object), or
the open() and send() methods of XMLHttpRequest, are all public, because you
were able to use them. Each class can also contain private members, which are
meant for internal usage only and aren't visible from outside.
Inheritance
Inheritance allows creating classes that are specialized versions of an existing
class. For example assume that you have the Car class, which exposes a default
interface for objects such as myCar, johnsCar, or davesCar. Now, assume that
you want to introduce in your project the concept of a supercar, which would
have similar functionality to the car, but some extra features as well, such as
the capability to fly!
If you're an OOP programmer, the obvious move would be to create a new class
named SuperCar, and use this class to create the necessary objects such as
mySuperCar, or davesSuperCar. In such scenarios, inheritance allows you to
create the SuperCar class based on the Car class, so you don't need to code all
the common features once again. Instead, you can create SuperCar as a
specialized version of Car, in which case SuperCar inherits all the
functionality of Car. You would only need to code the additional features you
want for your SuperCar, such as a method named Fly. In this scenario, Car is
the base class (also referred to as superclass), and SuperCar is the derived
class (also referred to as subclass).
Inheritance is great because it encourages code reuse. The potential negative
side effect is that inheritance, by its nature, creates an effect that is known
as tight coupling between the base class and the derived classes. Tight
coupling refers to the fact that any changes that are made to a base class are
automatically propagated to all the derived classes. For example, if you make a
performance improvement in the code of the original Car class, that improvement
will propagate to SuperCar as well. While this usually can be used to your
advantage, if the inheritance hierarchy isn't wisely designed such coupling can
impose future restrictions on how you can expand or modify your base classes
without breaking the functionality of the derived classes.
Polymorphism
Polymorphism is a more advanced OOP feature that allows using objects of
different classes when you only know a common base class from which they both
derive. Polymorphism permits using a base class reference to access objects of
that class, or objects of derived classes. Using polymorphism, you can have,
for example, a method that receives as parameter an object of type Car, and
when calling that method you supply as parameter an object of type SuperCar.
Because SuperCar is a specialized version of Car, all the public functionality
of Car would also be supported by SuperCar, although the SuperCar
implementations could differ from those of Car. This kind of fl exibility gives
much power to an experienced programmer who knows how to take advantage of it.
Object-Oriented JavaScript
Objects and classes are implemented differently in JavaScript than in languages
such as C#, VB.NET, Java, or C++. However, when it comes to using them, you'll
feel on familiar ground. You create objects using the new operator, and you
call their methods, or access their fi elds using the syntax you already know
from C#. Here are a few examples of creating objects in JavaScript:
// create a generic object
var obj = new Object();
// create a Date object
var oToday = new Date();
// create an Array object with 3 elements
var oMyList = new Array(3);
// create an empty String object
var oMyString = new String();
Object creation is, however, the only signifi cant similarity between JavaScript
objects and those of "typical" OOP languages. The upcoming JavaScript 2.0 will
reduce the differences by introducing the concept of classes, private members,
and so on, but until then we have to learn how to live without them.
Objects in JavaScript have the following particularities. In the following pages
we'll discuss each of them in detail:
-
JavaScript code is not compiled, but parsed. This allows for fl exibility when
it comes to creating or altering objects. As you'll see, it's possible to add
new members or functions to an object or even several objects by altering their
prototype, on the fly.
-
JavaScript doesn't support the notion of classes as typical OOP languages do.
In JavaScript, you create functions that can behave—in many cases—just like
classes. For example, you can call a function supplying the necessary
parameters, or you can create an instance of that function supplying those
parameters. The former case can be associated with a C# method call, and the
later can be associated with instantiating a class supplying values to its
constructor.
-
JavaScript functions are fi rst-class objects. In English, this means that the
function is regarded, and can be manipulated, just as like other data types.
For example, you can pass functions as parameters to other functions, or even
return functions. This concept may be diffi cult to grasp since it's very
different from the way C# developers normally think of functions or methods,
but you'll see that this kind of fl exibility is actually cool.
-
JavaScript supports closures.
-
JavaScript supports prototypes.
Also read
Explain
an object, class and Method.
An object is an entity that keeps together state and behaviors.
For instance, a car encapsulates state such as red color, 900 cc etc and
behaviors as 'Start', 'Stop' etc., so does an object...............
Define
Encapsulation and Information Hiding in OOP.
Encapsulation means keeping actions and attributes together under a single unit.
This can also be understood using a motor bike example. A bike has actions such
as 'switch on light', 'horn' etc. and attributes such specific color, size,
weight etc..............
Explain Inheritance
and Polymorphism in OOP.
Inheritance concept in OOP allows us to create a new class using an existing
one. It also allows the new class to add its own functionality............
What is the relation between Classes and Objects? Explain different properties
of Object Oriented Systems. What is difference between Association, Aggregation
and Inheritance relationships? Explain the features of an abstract class in
NET. Difference between abstract classes and interfaces Similarities and
difference between Class and structure in .NET Features of Static/Shared
classes. What is Operator Overloading in .NET?.............
|