Quick Index
Overview


Object oriented software is all about the objects.

Example
Imagine all the objects at work on a small map (lines, points, text, etc).

No matter the oo software, there will be large numbers of objects in action.
Rectangles
Let's assume that the rectangular "block" areas in the map are rectangle objects.

So a mapping system would have millions of such rectangle objects (for a large area).
Rectangles Type
We would not want to code up a million rectangles (job security?).

What we do is come up with a general object type, and we only need to code it up once.

Then other code (e.g. the "mapping code") would take our type and construct as many rectangles as is desired.


How to Code Class


In oo languages like JavaScript an object type is coded as what we call a class.

We use classes for object modeling as we discussed above. We can also think of classes is how we organize our code.

JavaScript now provides a coder-friendly syntax for classes (this was not always the case).

Here is a step-by-step example of how to code a class:


Here is the complete project source code for the example.

Gotcha (keyword 'this') 🐞


We see the keyword "this" used a lot in the examples.

The keyword "this" is referring to the object instance we are coding for:


In JavaScript (and Python, others) "this" is explicit (required).

In some languages (e.g. Java) it is implicit (optional). Which leads to the possible gotcha if we are used to the implicit approach.

Let's zoom in on a couple methods from this pages Rectangle example:

Instance Variables
We use "this" to access instance variables from self (the object type we are coding in).

Which means we are getting the ivar value from "this" instance (it is the target for the access).
getArea() {
	return this.width * this.height;
}
Instance Methods
We use "this" to send messages to self (the object type we are coding in).

Which means we are sending the message (instance method) to "this" instance (it is the target who receives of the message).
toString() {
	return '' + this.getWidth() + 'x' + this.getHeight()
		+ ' area=' + this.getArea();
}