jQuery: inspecting objects and create a reflection API

jQuery already provides some reflection-like structures to gather information about some JavaScript components. However, we can use the extensibility of the library to get metadata from objects or, if you prefer, classes. More specifically, we want to know if a given member of an object is a property, a method or another object.

JavaScript: the Factory design pattern

The Factory design pattern is designed to create new object instances depending on the argument passed to the constructor. In JavaScript, the implementation of this design pattern is rather straightforward. All we have to do is to create a new function which accepts an object as its argument. Depending on the type of object passed in, it will return the appropriate object instance or an empty object if no argument has been specified.

Object oriented programming (OOP) in jQuery

Object Oriented Programming or OOP with jQuery: there's a plugin that does much of the heavy-lifting for you when dealing with objects. I said objects, not classes, because JavaScript is a class-free language, at least if we think of classes using the traditional approach of Java, C++ and C#. To add an extra level of confusion, some developers use terms such as super-class instead of parent class to refer to a particular JavaScript pattern used to handle inheritance. It's better not to use the term class at all to avoid any possible confusion. In JavaScript there are only objects, such as arrays, functions, numbers and so on. Objects not classes.

jQuery: OOP and code organization

The more I study jQuery, the more I convince myself of the importance of OOP with jQuery. I linked this presentation a couple of months ago but I'd like to link it even now, just after I finished an important client-side project with jQuery. You can't build up a complex web app with procedural code without getting mad whenever you have to make even a minor change to your code. Properties, not variables. Methods, not functions. Objects, then organization.

PHP 5 and the var keyword

Object-oriented support in PHP has been greatly improved with release 5. However, for backward compatibility reasons with older versions, some coding practices have been keeped. Among them there's the use of the var keyword in class definitions. Honestly, from an OOP perspective, I don't understand what this keyword is useful for. For example:

class myClass 
{
  var foo;
  var bar;
  var baz;
}

Seeing these declarations gets me confused, because I don't know at first glance what's the visibility of these members. Using a classic OOP, instead, makes life a lot easier and it's really much neater:

class myClass
{
  public $foo;
  protected $_bar;
  private $_baz;
}

So far I've never used var in my classes, and I have to say that my code is clearer and more intuitive. You should take into account the fact of getting rid of this old habit.