Object Oriented Javascript best practices?

JavascriptOop

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

First ought to read about the http://en.wikipedia.org/wiki/Prototype-based_programming">prototype-based programming so you know what kind of beast you're dealing with and then take a look at https://developer.mozilla.org/En/Javascript_Style_Guide">JavaScript style guide at MDC and https://developer.mozilla.org/en/JavaScript">JavaScript page at MDC. I also find best to force the code quality with a tool, ie. http://www.JavaScriptLint.com/">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 http://www.google.com/search?client=safari&rls=en-us&q=javascript+patterns&ie=UTF-8&oe=UTF-8">Google search: javascript patterns and http://www.mail-archive.com/[email protected]/msg24924.html">jQuery patterns.

Solution 4 - Javascript

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/

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Object Oriented Javascript for high quality applicatons and libraries

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questione-satisView Question on Stackoverflow
Solution 1 - Javascriptviam0ZahView Answer on Stackoverflow
Solution 2 - Javascripte-satisView Answer on Stackoverflow
Solution 3 - JavascriptBleadofView Answer on Stackoverflow
Solution 4 - JavascriptgregersView Answer on Stackoverflow
Solution 5 - JavascriptRyan FlorenceView Answer on Stackoverflow
Solution 6 - JavascriptPraveen AngyanView Answer on Stackoverflow