Recently I’ve been working heavily with JavaScript to implement full-blown rich user interfaces for web-based applications. In the past, I’ve used JavaScript and supporting libraries, such as jQuery and Jquery UI to introduce cool UI widgets to enhance my server side Java web applications.
But, as I’ve been introducing the MVC pattern to the browser using supporting JavaScript libraries, I’ve had to learn how to write object oriented modular JavaScript. And yes, you can do object oriented programming with JavaScript. So, I’d like to introduce some basic object oriented JavaScript concepts.
Initializer Objects
JavaScript is dynamic, meaning that when you define things such as function, expressions, or variables — they are defined. There’s not a compilation process to check syntax or typing (as there is in typed languages such as Java or C#). Object definitions are also dynamic and are simply an unordered collection of key/value pairs.
Here’s an expression that defines a JavaScript object:
var object = {};
This is referred to as a Initializer object, and it has no state or methods to execute. Since JavaScript is dynamic, properties can be added at any time. Age and name properties are added with the expressions below:
object.age = 49;
object.name = "Clifford";
alert(object.age +":"+ object.name);
Methods
Functions are also objects, and are used to create methods. Essentially, a function object is defined and assigned to an object property. The expressions below defines a print function, and assigns and executes the method:
object.print = function() { return object.age +":"+ object.name; };
console.log(object.print());
Using JSON Type Syntax
A complete object can be defined using JSON type syntax. Here’s an example of how a “person” object can be created in a single expression:
var person = { name: "david",
age: 40,
print: function() { return name + ":"+age}};
console.log(person.print());
Personally, my object oriented programming background comes from Smalltalk — dating myself — with the last decade using Java and C#. I’ve come to find out that the JavaScript community refers to this as a classical way of OO thinking. In the next section, I’ll introduce another way to define JavaScript objects, commonly referred to as the “classical” object approach.
Constructor Objects
Objects may also be defined so that they are created using the classical “new” operator, along with specifying initialization parameters. Any function that is assigned to a variable can be issued the new command, and an object will be created.
The example below shows how a constructor function is defined, and how it accepts name and age values that are assigned to the “Person” variable:
var Person = new function(name,age) {
this.name = name;
this.age = age;
this.print = function() {
return his.age +":"+ this.name;
};
}
An object can be created and used, as long as the “person” variable is in scope with the expressions below:
var person = new Person("Clifford",49);
person.print();
Object Prototypes
As you can see, JavaScript does not have classes as with other classical OO languages such as Java or C#. Instances are created using prototypes, and as such, all constructor object references have a prototype property reference that can be used to extend object implementations.
Consider the String global object reference. Its prototype reference can be used to extend its functionality with a repeat method as in the expressions below:
String.prototype.repeat = function(x) {
return count > 1 ? '' : new Arrray(count + 1).join(this);
};
Once extended, it can be used as followed:
"Hello".repeat(3);
Emulating Inheritance
JavaScript does not have an inheritance mechanism, but by using prototypes you may emulate it.
The example below defines two objects: Person and User. The User constructor object defines two attributes but inherits properties and methods from the “Person” object by assigning its prototype. Here is JavaScript carrying this out:
var Person = function() {
this.age;
this.name;
this.print = function() {
return "Age:"+this.age+" - "+"Name: "+this.name;
}
};
var User = function() {
};
function createUser() {
User.prototype = new Person();
var user = new User();
user.id;
user.password;
return user;
}
Usage of the user object is shown below:
var u = createUser();
alert(u.print() + "id:"+u.id + "password:"+u.password);
Emulating inheritance using initializer objects can be implemented by defining a method on a base object that dynamically copies properties/methods to a supplied object. This technique is done in the backbone.js framework to allow the base view object to be extended with sub-objects.
Here’s how a extend() method can be implemented in the previous example:
function extend(object) {
var base = new Person();
for (var attr in base) {
object[attr] = base[attr];
}
return object;
}
An object that extends a “Person” object definition can be done with this expression:
var user = extend({id:"abcd",password:"123"});
alert(user.print() + "id:"+user.id + "password:"+user.password);
Super is a reserved word in JavaScript, however it is not implemented. You’ll have to roll your own implementation for accessing parent objects in an inheritance chain.
I have shown you a very basic way to implement inheritance, but there are more nuances (such as overriding and super mechanism) that have to be considered. But hopefully this provides some context.
Getter/Setters?
Yes, JavaScript provides support for formal getter/setters. This was a late addition, but I am pretty sure all newer browsers support getter/setters. They mirror the C# implementation, as in Java you still have to implement them.
I really like the way the getter/setter code blocks are hidden. Here is how you would apply them to the name attribute of the example object that we’ve been working with:
var Person = function() {
this.age;
var name;
this.print = function() {
return "Age:"+this.age+" - "+"Name: "+this.name;
};
this.__defineGetter__("name", function(){
return value;
});
this.__defineSetter__("name", function(val){
value = val;
});
};
Getter/Setter methods are invoked just like attributes. Here’s an example:
Person person = new Person();
person.name = "Chris";
person.name;
Conclusion
If you are new to applying JavaScript as a general purpose programming language, then these basic object constructs should help you as you progress in applying modularity frameworks (such as require.js or backbone.js) and writing general purpose applications with JavaScript. Good luck!
– David Pitt, asktheteam@keyholesoftware.com