Wednesday, 25 April 2007

Object Oriented Javascript

I'm using a lot of Javascript in the project I'm currently working on. I don't really like it but it can be very useful sometimes. In order to make it easier I try to use the object oriented approach. Protoype.js library supports creating of an object oriented code by extending regular javascript objects with some additional functionality. You can find good examples at prototype's homepage but I also recommend this tutorial.

Having some background in a "real" OOP languages I did not have many difficulties with creating OO JS code. I did have, however, some problems with understanding how it works - I'm still not 100% sure about it ;). The issue I'm talking about is related to the scope of methods. I found myself trying to access some object's properties from the body of the methods, that could work in different context. If you have the same problem I would recommend reading the description of bind() method, that is introduced by prototype library.

It is also possible to write OO JS code without using prototype.js. There are good tutorials available here and here.

1 comment:

Sebastian Ryszard Kruk said...

two hints:

1) always use this. when referring to object attributes
2) when you use Prototype and its Ruby-style enumerators, be aware that "this" inside the loop is actually the Enumerator object not - your "this". I usually put
var thiz = this; before the loop-enumeration and refer to thiz instead.