X

On sale! Now!

$29.95 14.95


JavaScript Object Programming (JOP)

© 2 August, 2013, Martin Rinehart


For more book content, select (here or on the menu above):
Gateway Page for access to the rest of the online content, including links to internal and external (reference) resources,
Coding Tutorials for tutorials, chapters 2 through 6 in the book,
Using JSWindows for an engineer's fun buzz through JSWindows from the user's point of view,
JSW Examples to view the code behind the user tutorial,
JSW Doc for detailed engineer's doc, and
Source Code for the JSWindows system used in this book.

 

Buy JavaScript Object Programming

If you want the best price (for most buyers), click "Best Price" in the Amazon box.

If you have a discount code, order from the CreateSpace eStore.


top

 

Preview JavaScript Object Programming

Like to see for yourself? Free? Open the first three chapters in your browser. Right now!

Want to look at the backmatter? Appendix A is about ex nihilo classes. The Notes cite lots of references for the controversial statements. Check the backmatter.

Suggestion: File/Save, anywhere you like, and reopen with the Adobe Reader (the 2-page view is our favorite).

top
 

Learn More about JavaScript Object Programming

JavaScript Object Programming (JOP) is the book you want to start at the beginning and then proceed, step-by-step, into the highly productive world of JavaScript object programming. Here's what you will learn:

1 Objects

Why and how they took over the software world and what you can expect from them. Also, introduces an extended system built on objects and class-based inheritance, JSWindows. (You can try it yourself, here).)

Objects and Object-Oriented Programming Took Over

Objects came out of the research labs in the late '70s and early '80s. The first mainstream language supporting objects was Bjarne Stroustrup's C++ (from Bell Labs, where C was born), first available in 1983. It caught on among C programmers. (C was then the dominant language for programming personal computers, minicomputers and mainframes other than IBM mainframes.)

Today, the C++ object model has been implemented in newer languages, such as Java, and added to even very old languages, such as Basic, Cobol and Fortran. It has been extended in languages such as Python and Ruby.

Why Are Objects Ubiquitous?

In the book we cite three causes. The most important is that objects help reduce large programs to a group of small programs. As programming difficulty expands exponentially with program size, 10 small programs are much easier to write and debug than a single program of the same total length.

top

2 JavaScript Objects

Discusses built-in objects, ex nihilo (from nothing—object literals) through constructors and custom classes.

JavaScript's Built-In Objects

JavaScript beginners learn to use JavaScript's built-in classes like Math and Date. The former is really a library of useful routines (like Math.round() and Math.ceil()) all organized as the properties of Math. The Date function is a bit more like an object-oriented tool. The exact current time is, for example, encapsulated in a new Date() instance object.

Create JavaScript Objects "from Nothing"

"Ex nihilo" (literally, "from nothing") JavaScript objects can be instantiated from the Object() constructor or from JavaScript's object literal notation:

myObject = new Object();

The above line creates a new object. It has no properties. You could add data properties this way:

myObject.color = 'blue';
myObject.size = 'large';

Critically important when we move to object programming, these two lines do the same job as the above pair:

myObject['color'] = 'blue';
myObject['size'] = 'large';

You could also create the same object this way:

myObject = { color:'blue', size:'large' };

Create JavaScript Objects from Custom Constructors

If you wanted to create a family of widgets, and the important properties of widgets were their colors and sizes, you would start with a constructor function:

function Widget(color, size) {
	this.color = color;
	this.size = size;
}

With that constructor, you could create widgets this way:

widg1 = new Widget('blue', 'large');
widg2 = new Widget('red', 'small');

alert( widg1.color ); // 'blue'
alert( widg2.size ); // 'small'

top

3 Object Programming

What really separates JavaScript from C++ (and all the other class-based, "object-oriented" languages) is that your objects can be manipulated during execution. Add properties. Manipulate property names, not just values.

Object-Oriented Programming in Class-Based Languages

In C++ and its followers (Java, C#, VB, etc.) the "class" (a software module) defines the objects that are created as members of the class. It specifies what data properties they will have and what methods they can execute. It also provides the code for the methods (called "instance methods"). With object-oriented programming (OOP) the programmer can manipulate the values of the data properties during program execution.

With conventional OOP, the programmer cannot add or delete properties during execution. The programmer cannot add, delete or modify the instance methods. The programmer cannot work with the names of the properties.

Object Programming Defined

Object programming (OP) allows the programmer full access to the objects during execution of the program. Data values can be changed. Methods can be changed. Properties, both data and method, can be added or deleted. The programmer can manipulate property names as well as values.

Object Programming Demonstrated

You have a class, Extend that should inherit from another, Base. The Extend prototype has useful properties. Now you want to add the properties of the Base class to it. This little bit of code is all you need:

for (var name in Base.prototype) {
	Extend.prototype[name] = Base.prototype[name];
}

Object programming (OP) in JavaScript is brilliantly simple. It is easy to write and easy to read. This is the essential difference between JavaScript and class-based languages. (The fragment above creates new properties in the Extend object, assigning them both names and values. This would be nearly impossible in C++ or Java.)

top

4 Inheritance

What is it? How is class-based inheritance different from prototypal inheritance? (Ace the interview answer: "I use both class-based and prototypal inheritance. Which would you like me to talk about?")

Class-Based Inheritance

There are two kinds of inheritance in use today. By far the most common is the class-based inheritance pioneered in C++. To understand this we need to understand all of the meanings of the word "class" as used in the software field.

family
A "class" is a set of objects that all have the same properties. In practice this usually means the set of objects that were created by a single constructor. We call this type of class a "family."
class
A "class" may be the set of properties that a "family" of objects possess.
OOP class
A "class" may be the software that defines a "class" as defined above. We call this an "OOP class." OOP classes commonly provide a constructor (function that creates new members of the family) and instance methods that can be called for each member of the family. Most OOP classes can also have their own properties. In Java, these are called "class statics" from the "static" keyword used to define them.

Any two classes (second definition) may have one of these relationships:

  • They have no properties in common.
  • The two sets of properties have some overlap. (Both classes have some properties shared with the other class, some not shared.)
  • One class is a superset of the other. The subset class has no properties not also included in the superset class.

(To be complete, both classes could have the same set of properties. Most programmers would write a single class for this case.)

In the book, Figure 4-1 shows these relationships:

Drawing of classes with overlapping property sets.

Class-based inheritance is used in the third case, where one class is a subset of another. In the book Figure 4-2 shows this relationship.

Drawing of classes where one (called "Extend") is a superset of another (called "Base").

In this case the prototypal terminology says that Extend "inherits" from Base. In class based languages there is normally a special provision to describe this relationship. In Java, the OOP class software would say that Extend extends Base. C++ would tersely declare: Extend: Base.

Prototypal Inheritance

In the Self language (one of the principle parent languages of JavaScript) one object serves as the prototype of another object. We say that the superset object "inherits" from the subset (prototype) object.

JavaScript's Inheritance

JavaScript uses the term "prototype" to indicate an object, referenced by the constructor, from which each family member will share properties. This allows an entire family to "inherit" from a base object.

To summarize, in class-based OOP, "inheritance" refers to the assumption by an extending class of all the data and method properties of a base class. In pure prototypal inheritance, one object assumes all the properties of a base prototype object. In JavaScript, a family (first definition of "class") inherits the properties of a prototype object.

top

5 JavaScript Inheritance

How do you program class-based and prototypal inheritance?

In this short summary we cannot squeeze all of Chapter 5. A few words will have to suffice.

Inheriting Data Properties in JavaScript

JavaScript constructors, called with the "new" operator, perform some special operations that you do not want repeated in both a base and an extending class. We therefore recommend coding an init() method, separate from the constructor, that performs the initializations you require. Your full constructor then looks like this:

function Constructor(params) {
    Constructor.init(this, params);
}

Constructor.init = function(object_to_init, params) {
    // your initialization logic here
}

This is not quite as simple as just coding the Constructor() function. But when you want class-style inheritance, it lets you code this:

function Base(params) {
    Base.init(this, params);
}
Base.init = function (object_to_init, params) {
    // your logic here
}

function Extend(params) {
    Base.init(this, params);
    // additional logic here
}

If a third class might use Extend as its base, then you would break the Extend() constructor into a near-empty constructor and an init() function. Repeating this technique lets you write an inheritance chain of any length.

Inheriting Instance Methods in JavaScript

In some ways, the data properties are the easy ones. You typically want each object to have its own data properties. You do not, however, want each object to have a copy of each instance method. It is better to copy the class-based OOP approach of placing all the instance method code in one place where all instances can access it. In JavaScript, the place analogous to the OOP class module is the constructor's prototype property.

If you want all the instances to have access to a single code base, just place the method code in the prototype. If your objects will be created by the Constructor() function, this is the technique:

function Constructor(params) {
    // initialize, typically using an init()
}

Constructor.prototype.method_name = function (params for the method) {
    // method logic goes here
}

Prototypal Inheritance Code

To "inherit" from a prototype object, simply assign that object to the constructor's prototype property:

Constructor.prototype = prototype_object;

(Actually, the above line will destroy the constructor property that is provided by default in the prototype object. See the section (Chapter 3 above) on object programming for an improved version.)

top

6 Inheritance Alternatives

Most inheritance is forced to fit because class-based languages don't have a good set of tools. JavaScript has a marvelous set of tools and never needs to be forced into inheritance.

Multiple Inheritance

One of the most difficult problems with inheritance is that sometimes there can be more than one possible base class. In the book, Figure 6-1 illustrates the circumstance.

Drawing showing two base classes with one extending class.

This raised questions. Which base-class constructor should run first? What happens if B2 depends on values in B1 and vice-versa?

Worse, there is the diamond inheritance pattern. A is extended by B1 and by B2. B1 and B2 are both extended by C. (This pattern proved surprisingly common.)

Interfaces

Java (born 1995, partly to simplify C++ for use on the internet) introduced "interfaces," as one way to avoid the complexities of multiple inheritance. Originally documented as a sort of poor man's substitute for multiple inheritance, interfaces are now considered by many to be one of the fundamentals of object-oriented programming.

A Java interface is a definition of a class API. The methods are defined (name, calling arguments, return types) but not implemented. It is up to an implementing class to provide the code. One now-famous software design book told us to code to the interface, not to the implementation.

Capabilities

Our book introduces what we call "capabilities" in Chapter 6. A "capability" is similar to a Java interface, but with the methods implemented. On top of this, a capability includes the logic needed to graft itself onto an existing class. From Java, we borrowed the "implements" keyword as a method for objects that wish to avail themselves of capabilities:

my_class.implements('capability_name');

Like Java's interfaces, capabilities reduce or eliminate the complexities of multiple inheritance. They frequently let the designer reduce the length of inheritance chains.

Mixins

One of the oldest JavaScript-specific design patters, the "mixin" is very similar to our capability. The programmer uses object programming to add a set of new properties (commonly method properties) to a class. Like capabilities, a single mixin could be introduced to multiple classes. Again, the end result is that there is less code, or the individual code modules are shortened making for easier maintenance and fewer bugs.

top

7 Designing for JavaScript

We discuss a fundamental principle: making JavaScript objects fit the reality your systems model (not trying to force reality to fit class-based tools).

These four recommendations emerge from our work.

Use ex nihilo Objects Constantly

JavaScript liberates the object from the OOP class. When it is no longer necessary to write an OOP module to support each object, objects become much more commonly useful. We use them as regularly as we use arrays.

Use Composition Liberally

Just as objects help break down long programs into smaller, more manageable parts, objects can help break down objects into smaller, more manageable parts. Examples in the book illustrate, for example, breaking the borders out of screen objects as a separate object class.

Use Capabilities Liberally

Capabilities model an essential element of reality: different types of objects can do the same thing. Dogs, cats and elephants can all speak. On-screen objects can all have draggable title bars. A title bar capability fits windows, dialog boxes, panels within dialogs, and so on. Again, it can be programmed separately in a smaller, more manageable way.

Use Inheritance Conservatively

In OOP programming, inheritance features prominently through lack of alternative tools. JavaScript has an excellent object programming capability that lets the programmer create other tools as needed. Class-based inheritance should only be used when the reality being modelled is an object family that has a superset of the properties of another object family. There is no need, in JavaScript, to force this relationship on your object families.

top

About the Book

And did we mention, it's a short book? And did we mention the programming tutorials? (There's code to write, and there are completed programs to look at online, if you get stuck.) And did we mention that the JSWindows system, (it uses extensive inheritance) has all its code online for you to study?

The next step is up to you.



top

Feedback: MartinRinehart at gmail dot com
# # #