Javascript OOP made simple

Javascript is a really powerful tool, and you should master it if you wanna be part of that web 2.0 wave. But when you start to get a lot of code it soon starts to smell. Unless…

Try this : Prototype, if your not yet using it or another Javascript framework.

You’ll then be able to give your code a more clean structure, like classes:

var MyClass = Class.create();
MyClass.prototype = {
  initialize: function(first, second) {
    // called when newing an instance
  myMethod: function(args) {
    // woohoo a class method!

Classes are defined in an hash with a referenced function.

Now split your hanging javascript function in classes or namespace:

var MyNamespace = {
  myFunction: function() {

You can then refactor all your DOM events management with: Event.observe. No more onclick="...", just simple, clean code, that works on “all” browsers.

One note, if you’re hooking an event to an instance method, you sould bind the function to the current instance:

Event.observe('mybutton', 'click', this.onClick.bind(this));



1 Comment

Filed under js

One response to “Javascript OOP made simple

  1. Pingback: Interesting finding - 03/15/2007 « Another .NET Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s