Object Oriented programming in JavaScript PART4

Pattern 5: “Crockford” Patterns

Continued from part 3

However, there’s something to be said for having constructor functions. Having a constructor function create an object for us gives to that encapsulation we want and makes the process easier; we don’t have to worry about wiring up the right things; it just works.

Along these lines, we’re going to discuss two patterns that Douglas Crockford talks about in his presentation Function the Ultimate, which is part of his series, Crockford on JavaScript.

Continue reading

OOP in JavaScript PART3

Pattern 3: Classical Pattern

(Continued from PART2)
As you know, JavaScript doesn’t support classical inheritance. However, a lot of developers are used to classical inheritance from working with languages like Java, PHP, or Ruby. The good news is that JavaScript is so powerful that we can actually simulate a classical model.

The thing about this is that, since it’s not built in, we have to create (or find) a library that adds the classical features like super methods, and easy inheritance. It’s reasonably complicated to create this kind of thing, so we’re going to work with two already-created libraries: Base.js and Mootools. I’ll mentions right here, though, that they aren’t the only ones that do this; if you’re interested in this topic, you might want to check out the function John Resig made to do this. Also, the Dojo Toolkit offers some functionality very similar to Mootool’s.

Continue reading

Object Oriented Programming in JavaScript PART2

Pattern 1: Modules

(This is PART2 of the original post Object Oriented programming in javascript)
The first pattern we’re going to look at is the Module Pattern. Here are a couple of the main features of the module pattern:

  • One-Time Use: Objects that you create with the module pattern are for one-time use. What this means on the web—where you aren’t running JavaScript on more than one page at a time, and not keeping state between refreshes—is that you’ll only have one instance. A module isn’t a little factory that creates objects; it creates a single, specialized object of which there will only be one on a page.
  • No Inheritance: The module pattern doesn’t support inheritance by default. Of course, this doesn’t mean it’s impossible to inherit from it. After all, a module returns a single object, and you can inherit from any object. But that’s outside of the module pattern.
  • Private variable and functions: This feature is almost the whole point of using the module pattern. If you just need a unique object, just use an object literal. However, what if you want to hide values or functionality? An object literal doesn’t offer any way to hide that stuff, so we’ll do it with closure … which is what the module pattern is, in essence.

So, let’s actually create a module.

Continue reading