Object-Oriented JavaScript: Part 2 | Page 2
[previous] [next]
Object-Oriented JavaScript: Part 2
C# and JavaScript Classes
For the purpose of demonstrating a few more OOP-related concepts, we'll use another class. Our new class is named Table
, and it has two public fields (rows
, columns
), and one method, getCellCount()
. The getCellCount()
method should return the number of rows multiplied by the number of columns. The class constructor should receive two parameters, used to initialize the rows
and columns
fields. This class could be represented by the class diagram in Figure 3-3.
The C# version of this class would look like this:
You'd instantiate and use the class like this:
[ In a production-quality C# implementation you may want to implement rows
and columns
as properties with get
and set
assessors, rather than public fields. That implementation, however, would make its JavaScript version more complicated than necessary for the purposes of our examples. ]
The Table
class can be easily implemented in JavaScript as shown in the following code snippet, and it would resemble very much its C# version:
After having declared the object, we can instantiate it by using the newoperator and use its properties and methods:
There are a few subtle points you need to notice regarding the JavaScript implementation of Table:
|
The last mentioned problem is commonly referred to as a "memory leak", although technically it's just inefficient JavaScript object design. When we design our JavaScript "classes" as we do in typical OOP languages, we don't need each class to create its own set of methods. It's only state (fields) that need to be individual, and not methods' code. The good news is that JavaScript has a neat trick that we can use to avoid replicating the inner function code for each object we create: referencing external functions.
Referencing External Functions
Instead of defining member functions ("methods") inside the main function ("class") as shown earlier, you can make references to functions defined outside your main function, like this:
Now, all your Table
objects will share the same instance of getCellCount()
, which is what you will usually want.
[previous] [next]
URL: