Article
Rethinking JavaScript Objects
With this method defined, we can now do the following:
function ClassA () {
}
function ClassB() {
this.extends(new ClassA());
}
It is important to note that this method should be called first in your class (constructor) definition. Any additions should be made after this initial call. Also note that you must instantiate an object of the class you want to inherit from; you cannot simply pass in the class name itself. For example, this is incorrect:
function ClassA () {
}
function ClassB() {
this.extends(ClassA); //INCORRECT!!!!
}
This powerful new function also opens up the possibility of inheriting from two different classes and retaining the union of all properties and methods from the two. Let’s say ClassZ wants to inherit from both ClassY and ClassX. In this case, our code would look like this:
function ClassX (sMsg) {
this.message = sMsg;
}
function ClassY (sName) {
this.name = sName
}
function ClassZ() {
this.extends(new ClassX(“Hello World”));
this.extends(new ClassY(“Nicholas C. Zakas”));
}
var oTest = new ClassZ();
alert(oTest.message);
alert(oTest.name);
This method has greatly decreased the amount of time I’ve spent debugging inheritance problems because, instead of having four lines of code to get right, there’s now only one.
Rethinking Properties
In Java, we don’t often allow people direct access to properties. For instance, rarely do you see something like this:
Class ClassA {
public string message;
}
ClassA Test = new ClassA();
Test.message = “Hello world”;
Instead, classes are typically defined with getters and setters for each attribute (which is itself private), such as this:
Class ClassA {
private string message;
public void setMessage(String msg) {
this.message = msg;
}
public String getMessage() {
return this.message;
}
}
ClassA Test = new ClassA();
Test.setMessage(“Hello world”);
This is a much better way to handle the properties of an object because of the extra measure of control it provides over the data. Yet in JavaScript, we often see this:
function ClassA() {
this.message = “”;
}
var Test = new ClassA();
Test.message = “Hello world”;
In an effort to make my JavaScript classes more Java-like, I came to the conclusion that this process could be made simpler if I could just define a property and create a getter and setter automatically.