253

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.

gnovice
  • 125,304
  • 15
  • 256
  • 359
Bite code
  • 578,959
  • 113
  • 301
  • 329
  • I'm looking for something like this as well. If you have links to more reading, please do post them.. Thanks – AJ. Jun 02 '09 at 18:15
  • 2
    Maybe "object oriented" in title should be replaced to "modern". – viam0Zah Aug 28 '10 at 09:10
  • 43
    Hmmm, 79 upvotes, 82 favs, 91 upvotes on the answer... yet this was closed as not constructive... why?? – Brett Rossier Mar 16 '12 at 18:05
  • You can vote to reopen it @pheedbq. I think like you that it's a good question. – Bite code Mar 16 '12 at 19:23
  • Don't have the reputation points yet :\, otherwise I would. – Brett Rossier Mar 16 '12 at 20:50
  • 1
    I wrote a simple class porting C++ OOP Features to javascript with a simple and natural syntax. See my answer here: http://stackoverflow.com/a/18239463/1115652 –  Aug 14 '13 at 18:27
  • 14
    This type of question always gets closed. I understand the reasons for this, but as they are important questions, and always popular (and since I always find them when I have a similar question), I wonder if anyone can direct us to the proper venue for asking them? – K. P. MacGregor Oct 16 '13 at 01:40
  • 1
    Seriously - what does this site exist for if not to answer questions or provide pointers? SE needs to explain, specifically, WHY a question was closed with something more than boilerplate. – lonstar Jan 19 '14 at 00:08
  • I guess closing questions gets you a badge. Not one I'd want. – James Apr 09 '14 at 14:59
  • 2
    @BrettRossier What good is power if you don't wield it? SO is the live demonstration of how a democratic pecking order works. Surely some psychologists are looking into it... –  Jun 14 '14 at 15:11

6 Answers6

289

Using `var` or not

You should introduce any variable with the var statement, otherwise it gets to the global scope.

It's worth mentioning that in strict mode ("use strict";) undeclared variable assignments throws ReferenceError.

At present JavaScript does not have a block scope. The Crockford school teaches you to put var statements at the beginning of the function body, while Dojo's Style Guide reads that all variables should be declared in the smallest scope possible. (The let statement and definition introduced in JavaScript 1.7 is not part of the ECMAScript standard.)

It is good practice to bind regularly-used objects' properties to local variables as it is faster than looking up 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 performance advantages, and also allows your code to be minified and obscured at a high level. You can also ensure it won't pollute the global namespace. Wrapping Functions in JavaScript also allows you to add aspect-oriented behaviour. 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 functions are first-class objects, and you can do anything with them, as with 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. JavaScript has four object-creation 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 pick up some JavaScript frameworks, study their conventions and style, and find those practices and patterns that best fit you. For instance, the Dojo Toolkit provides a robust framework to write object-oriented JavaScript code which even supports multiple inheritance.

Patterns

Lastly, 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.

Community
  • 1
  • 1
viam0Zah
  • 25,949
  • 8
  • 77
  • 100
  • 1
    "JavaScript has four object-creation patterns: pseudo-classical, prototypical, functional, and parts" - I would really appreciate a summary of the pros and cons here. – BadHorsie Mar 11 '15 at 11:42
  • 2
    "The `let` statement and definition introduced in JavaScript 1.7 is not part of the ECMAScript standard." Now it's part of ES6. – Michał Perłakowski Mar 24 '16 at 22:49
13

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 answers 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. Therefore, 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: inner functions won't be able to access "this" because of the funny JS scope. Douglas Crockford recommends to bypass this limitation using a conventional local variable named "that". So it becomes

function MyObject() {

    var that = this;

    this.myMethod = function() {

        jQuery.doSomethingCrazy(that.callbackMethod);

    };

};

Do not rely on automatic end of line

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

Thanatos
  • 42,585
  • 14
  • 91
  • 146
Bite code
  • 578,959
  • 113
  • 301
  • 329
8

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
  • 1,157
  • 1
  • 9
  • 19
5

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
  • 12,523
  • 8
  • 46
  • 41
5

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

Ryan Florence
  • 13,361
  • 9
  • 46
  • 63
  • 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. – Bite code Jun 03 '09 at 06:26
  • 2
    I think the MooTools object system is quite elegant and really helps me to keep my code organized/encapsulated. – awesomo Mar 22 '10 at 14:57
0

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

Object Oriented Javascript for high quality applicatons and libraries

Praveen Angyan
  • 7,227
  • 29
  • 34
  • 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. – Bite code May 25 '09 at 16:51