Assertfail

Simple object oriented JavaScript

30 Jul 2010

The jQuery approach is to avoid object orientation. This is an excellent way of avoiding bloat for small JavaScript hacks. If you’re starting to build JavaScript heavy applications then you might need to start organizing your code. The first thing you should learn is how to write jQuery plugins. Later on you will need to learn some simple object orientation. Here’s how:

function TigerType(name){
    var that = this; this.name = name; this.sound = "growl!";
    this.roar = function(){ return that.sound; };
}
var tigerInstance = new TigerType();
alert(tigerInstance.roar());

Note that I’m declaring a variable “that”. If you work with jQuery you know that this will be set to something else. By using a scoped variable you will avoid this problem. So what about inheritance? The simple solution is to use call or apply.

function TigerWithTeethType(name){
    var that = this;
    TigerType.call(this,name);
    this.bite = function(){ /*some code to bite the programmer ;)*/ };
}

Since TigerType is a function, call and apply can be used to execute it with the “this” of TigerWithTeethType. This way has the advantage of being simple and jQuery safe. You might also want to look into:

Try to avoid object orientation when writing JavaScript. If you’re doing small things then there is no need for the added complexity of object orientation (in JavaScript).

Tags


Comments

Do you want to send a comment or give me a hint about any issues with a blog post: Open up an issue on GitHub.

Do you want to fix an error or add a comment published on the blog? You can do a fork of this post and do a pull request on github.