Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping your javascript structured and tidy (as an OO programmer)

Tags:

javascript

oop

I've recently been playing with javascript, HTML5, chrome extensions, jQuery, and all that good stuff. I'm pretty impressed so far with the possibilities of javascript, the only thing I struggle with is structuring my code and keeping it tidy. Before I know it, functions are scattered all over the place. I've always done my programming in an object oriented manner (C++ and C#), and I find myself not being able to keep things tidy. It feels like I always end up with a bunch of static util functions, were I to 'think' in C#.

I've been looking for some information on objects in javascript, but it seems to come down to wrapping functions in functions. Is this a good way of structuring your codebase? On the surface it seems a bit hackish. Or are there other ways of keeping things tidy for an OO mindset?

like image 576
diggingforfire Avatar asked Dec 29 '11 21:12

diggingforfire


1 Answers

One important aspect to remember about Javascript is that it is a prototypical language. Functions can be objects, and anything can be put on the object, often affecting related objects in the process. There's no official way to 'extend' an object because of this. It's a concept that I still have a hard time understanding.

Javascript 'acts' like any other OOP language for the most part, with some exceptions, namely extending objects (http://jsweeneydev.net84.net/blog/Javascript_Prototype.html).

After extensive research, I did find a very, very light-weight way to simulate expanding objects (I'm using using it in my GameAPI). The first field is the parent object, the second is the object that expands.

extend  : function(SuperFunction, SubFunction) {

    //'Extends' an object

    SubFunction.prototype = new SuperFunction();
    SubFunction.prototype.constructor = SubFunction;
},

This link might clear up some problems and misconceptions: http://www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html

Personally, I tend to be anti-framework, and I haven't seen a framework yet that doesn't force the programmer to significantly change their programming style in this regard anyway. More power to you if you find one, but chances are you won't really need one.

My best advise is to try to adapt to Javascript's prototypical style, rather than force old methodologies on it. I know it's tricky; I'm still trying to myself.

Best of luck diggingforfire.

like image 64
Jeffrey Sweeney Avatar answered Sep 28 '22 02:09

Jeffrey Sweeney