Lazycoder

26Feb/081

Modern Javascript Development: constructors and objects

JavaScript doesn't have a "class" keyword or any formal class construct. Instead, functions are 1st class objects. When you write a function, you are essentially writing a constructor for a new object.
Here we are defining a object constructor called "newClass" and assigning some member values.

CODE:
  1. function newClass() {
  2.     this.name = "newClass";
  3.     this.options = {size:42};
  4. };
  5.  
  6. var myInstance = new newClass();
  7. alert(myInstance.name);
  8. alert(myInstance.options.size);

You can also specify arguments for the constructor just like any other function and assign the argument values to the objects members.

CODE:
  1. function newClassInitialzed(name, options) {
  2.     this.name = name;
  3.     this.options = options;
  4. };
  5. var anotherInstance = new newClassInitialzed("John", {size:42})
  6. alert(anotherInstance.name);
  7. alert(anotherInstance.options.size);

So what happens if you don't want to pass the name and options to the constructor every time? You can specify defaults for the member variables values using the logical OR ( || ) operator in JavaScript. The logical OR operator has a short-circuit which always returns "true" if the first argument is true.

CODE:
  1. function defaultArgValues(name, options){
  2.     this.name = name || "unknown";
  3.     this.options = options || {size:42};
  4. };
  5. var defaultArgsInstance = new defaultArgValues();
  6. alert(defaultArgsInstance.name);
  7. alert(defaultArgsInstance.options.size);

Since functions are first class objects, we can pass them as arguments in our constructors as well.