tags:

views:

2831

answers:

10

I'm finding myself coding a big project in Javascript. I remember the last one was quite an adventure because hacky JS can quickly becomes unreadable and I want this code to be clean.

Well, I'm using objects to construct a lib, but there are several ways to define things in JS, implying important consequences in the scope, the memory management, the name space, etc. E.G :

  • using var or not;
  • defining things in the file, or in a (function(){...})(), jquery style;
  • using this, or not;
  • using function myname() or myname = function();
  • defining methods in the body of the object or using "prototype";
  • etc.

So what are really the best practices when coding in OO in JS ?

Academic explanations really expected here. Link to books warmly welcome, as long as they deal with quality and robustness.

EDIT :

Got some readings, but I'm still very interested in answers to the questions above and any best practices.

A: 

Use whatever your JS framework does for consistency and because they had some reasoning behind it.

If you're trying to make your own JS framework, you probably already know the answers.

If you're trying to live without one: why?

alamar
I'm not trying to make a framework, and I do use JQuery. There are 1000 reasons to write a lib ;-) I want to know the what, the why and the how behind good implementations, and use them when a pre built solution does not exist yet.
e-satis
Well, write it in jquery way, then.
alamar
@alamar: you'd improve your question a lot if you explained the "write it in jquery way" part and provided an example for that is related to the question.
Török Gábor
+2  A: 

I wrote an article some time ago explaining some OO stuff. Maybe you find it useful: http://sebagr.com/2009/02/28/classes-in-javascript.

Bear in mind that takes care only of OO issues, while many things you're asking here are not strictly OO.

Seb
Ok, this is not about best practices but there are some things every body should know in there. +1
e-satis
+11  A: 

Search for the Google Tech Talk by Doug Crockford "Javascript: The Good Parts" He has a book out, too - and other lectures online from Yahoo, I believe.

Anon
Ah, that's the thing I am looking for. Thks a lot !
e-satis
Read the book. It's fine, but not as leading as expected. Once again, it's about the basics. I'm gonnar check javascript ninja, to see...
e-satis
A: 

Here's a book that covers most of the bases:

Object Oriented Javascript for high quality applicatons and libraries

Praveen Angyan
Thanks, but I am not looking for the basis. I can code (dirty) runnable JS. Or at least most of the time :-) I need guidances to write the same code, but properly.
e-satis
+2  A: 

This related question might be useful to you: JavaScript Coding Standards

mikelong
+2  A: 

First ought to read about the prototype-based programming so you know what kind of beast you're dealing with and then take a look at JavaScript style guide at MDC and JavaScript page at MDC. I also find best to force the code quality with a tool, ie. JavaScript Lint or other variants.

Best practices with OO sounds more like you want to find patterns than concentrate on code quality, so look at Google search: javascript patterns and jQuery patterns.

Bleadof
+33  A: 

Using `var` or not

You should introduce any variable with the var statement, otherwise it gets to the global scope. It worth binding regularly used objects' properties to local variables as it is faster than looking up always the whole scope chain. (See Optimizing JavaScript for extreme performance and low memory consumption.)

Defining things in the file, or in a `(function(){...})()`

If you don't need to reach your objects outside your code, you can wrap your whole code in a function expression—it's called the module pattern. It has advantages in performance, and also allows your code to be minified and obscured in a high level. Even you can ensure it won't pollute the global namespace. Wrapping Functions in JavaScript also allows to add aspect oriented behavior. Ben Cherry has an in-depth article on module pattern.

Using `this` or not

If you use pseudo-classical inheritance in JavaScript, you can hardly avoid using this. It's a matter of taste which inheritance pattern you use. For other cases, check Peter Michaux's article on JavaScript Widgets Without "this".

Using `function myname()` or `myname = function();`

function myname() is a function declaration and myname = function(); is a function expression assigned to variable myname. The latter form indicates that function are first-class objects, you can do anything with them like a variable. The only difference between them is that all function declarations are hoisted to the top of the scope which may matter in certain cases. Otherwise they are equal, function foo() is a shorthand form. Further details on hoisting can be found in the JavaScript Scoping and Hoisting article.

Defining methods in the body of the object or using "prototype"

It's up to you as well. JavaScript has four object creating patterns: pseudo-classical, prototypical, functional, and parts (Crockford, 2008). Each has its pros and cons, see Crockford in his video talks or get his book The Good Parts as Anon already suggested.

Frameworks

I suggest you to pick up some JavaScript frameworks (if not already did so), study their conventions and style, and find those practices and patterns the best fit you. For instance, the Dojo Toolkit provides a robust framework to write object oriented JavaScript codes which even supports multiple inheritance.

Patterns

At last, there is a blog dedicated to explore common JavaScript patterns and anti-patterns. Also check out the question Are there any coding standards for JavaScript? in Stack Overflow.

Török Gábor
Can you please tell me why was it down voted? Critics are always welcome.
Török Gábor
@Török Gábor: I guess it was because you didn't explain about the 'etc..' part
andho
I explained the 'etc' part.
Török Gábor
A: 

You might want to check out Secrets of the JavaScript Ninja by John Resig (jQuery). "This book is intended to take an intermediate JavaScript developer and give him the knowledge he needs to create a cross-browser JavaScript library, from the ground, up."

The draft is available through the publisher: http://www.manning.com/resig/

Douglas Crockford also has some nice JavaScript articles on his homepage: http://www.crockford.com/

gregers
+1  A: 

I am going to write down some stuffs that I read or put in application since I asked this question. So people reading it won't get frustrated, as most of the anwsers are RTMF's in disguise (even if I must admit, suggested books ARE good).

Var usage

Any variable is supposed to be already declared at the higher scope in JS. So when ever you want a new variable, declare it to avoid bad surprises like manipulating a global var without noticing it. Therefor, always use the var keyword.

In an object make, var the variable private. If you want to just declare a public variable, use this.my_var = my_value to do so.

Declaring methods

In JS, they are numerous way of declaring methods. For an OO programmer, the most natural and yet efficient way is to use the following syntax :

Inside the object body

this.methodName = function(param) {

/* bla */

};

There is a drawback : inners functions won't be able to access "this" because of the funny JS scope. Douglas Crockford recommand to bypass this limitation using a conventional local variable nammed "that". So it becomes

function MyObject() {

    var that = this;

    this.myMethod = function() {

        jQuery.doSomethingCrazy(that.callbackMethod);

    };

};

Do not rely on automatic en of line

JS try to add automatically ";" at the end of the line if you forget it. Don't rely on it, you'll get errors that are a mess to debug.

e-satis
+2  A: 

I often feel like the only guy here who uses MooTools for my javascript.

It stands for My Object Oriented Tools, mootools.

I really like their take on OOP in javascript. You can use their class implementation along with jquery too, so you don't have to ditch jquery (though mootools does it all just as well).

Anyway, give the first link a good read and see what you think, the second link is to the mootools docs.

MooTools & Inheritance

MooTools Classes

rpflo
I don't thing trying to bend a language to make it fit you old habbit is a good thing. It's like this people in C, using # to replace make it looks like fortran, or else. I think you should try to learn the way the language works (and its best practicesà, and use it the way that not disturb you too much. But not change it, really.
e-satis
I think the MooTools object system is quite elegant and really helps me to keep my code organized/encapsulated.
awesomo