Let’s go back to the very first example that demonstrated the advantage of using less procedural and more OO techniques. Remember building that “person” object? Check out Part One here.
Editor's Note: This article is excerpted from chapter 10 of Open Source Starter Guide for IBM i Developers, by Pete Helgren.
Turns out that is a very ES5 way of doing things. If you are using the latest version of Node.js and using a Web browser that actually works, like Chrome or Firefox, you can use some of the “class” concepts I talked about in chapter 5. Imagine building a Person class that defines a constructor to create a person object as well as a method to output the person information. That class might look like this:
Again, this is a wee bit more code than before, but the goal here is that in the long term we’ll make up for slightly longer code that defines the class with less code to implement the class. What is really nice about this is the constructor and the method. It is all self-contained, so when we build a person we already have an object that can talk about itself (maybe the class should be “Politician”). So this is how we would then construct one of these persons and get it to talk:
Output:
My name is Pete Helgren I am a 33-yr. old programmer that lives on 19001 Huebner road
(Apparently this person also lies about their age ... they are a politician!)
The ES5 aficionado will say “I can do that with an object by passing parameters to a function to set all the properties as well.” Well, yeah, that is the way most folks used to do it, but now we can also use inheritance with the “extend” keyword, so that if we have a class that we want to extend with another class’s function, we can do that!
Let’s say this Person class extends the Employee class. The Employee class has the following:
Note that the Employee class has a constructor as well, so we’ll need to accommodate that when we construct the Person class that extends Employee. So our complete class would look like this:
Then the output would be:
My name is Pete Helgren I am a 33-yr. old programmer that lives on 19001 Huebner road
Killer! I make 1.99 each month.
How sweet is that? By just extending the class with another class, I inherit the data storage and the methods of that class. Hopefully, you are beginning to get the big picture here. In many cases, we build programs that use and reuse code, not only within the same program but across programs as well. By creating classes, we can reuse common functions just by extending the class with another class. Very often, you will develop quite a few utility programs that handle I/O, or validation or, in the cases of security, encoding/decoding and verifying information. Classes allow us to reuse use our commonly used stuff.
Next time: Part 3 - Arrays and Hashes. Can't wait? You can pick up Peter Helgren's book, Open Source Starter Guide for IBM i Developers at the MC Press Bookstore Today!
LATEST COMMENTS
MC Press Online