Constructors
A constructor allows you to initialize every object of a class by executing code whenever a new instance of the class is created. Listing 3 changes our custom.javaworld.Worker class to add a constructor.
Listing 3. Adding a constructor
dojo.declare("custom.javaworld.Worker",null,{
firstName: "",
lastName: "",
constructor: function(fName, lName){
console.debug("Constructor of com.javaworld.Worker called");
this.firstName = fName;
this.lastName = lName;
},
work: function(){
console.log("Working");
}
});
var johnDoe = new com.javaworld.Worker("John","Doe");
console.log("First Name " + johnDoePerson.firstName);
console.log("Last Name " + johnDoePerson.lastName);
As you can see, we made one change in the custom.javaworld.Worker class to add a constructor member function. The constructor member function is special. It gets called whenever you create new instance of the class using the JavaScript's new operator. The constructor takes two arguments -- fName and lName -- and assigns these value to the member variables, which you access by using the this operator inside the class.
Inheritance
The ability to extend other classes is one of the basic features of object-oriented programming. Dojo handles all the requirements for setting up an inheritance chain. For example, when you create an instance of a class, Dojo calls the constructor of its superclass before calling constructor of the child class. Also, if you add a method to the child class with same name as that of the superclass, then the method in the child class overrides the method in the superclass.
Listing 4 creates a custom.javaworld.ITWorker class that extends custom.javaworld.Worker.
Listing 4. Extending a class
dojo.declare("custom.javaworld.ITWorker",custom.javaworld.Worker,{
constructor: function(fName, lName){
console.debug("Constructor of com.javaworld.ITWorker");
},
work: function(){
this.inherited(arguments);
console.log("Writing Code");
}
});
var johnDoe = new com.javaworld.ITWorker("John","Doe");
johnDoe.work();
Because we want ITWorker to extend the Worker class, Listing 4 passes the custom.javaworld.Worker class as the second argument when declaring the ITWorker class. Now when you create a new instance of ITWorker using the new operator, Dojo first invokes the constructor of Worker class. Also, the ITWorker class's work() method overrides the Worker class's work() method.
Suppose you need to invoke the overridden method of superclass first and then add some functionality in the child class method. In that case then you can use the.inherited() construct to invoke an inherited method of the superclass. In Listing 4, when you call the ITWorker class's work() method, it first invokes the Worker class's work() method, which prints "Working" on the console then prints "Writing Code" on the console. |