Share

From this page you can share Simple "Class" Instantiation in Javascript to a social bookmarking site or email a link to the page.
Social WebE-mail
Enter multiple addresses on separate lines or separate them with commas.
Simple "Class" Instantiation in Javascript
(Your Name) has forwarded a page to you from Ajaxonomy
(Your Name) thought you would like to see this page from the Ajaxonomy web site.

Simple "Class" Instantiation in Javascript

Tagged:  

John Resig has pulled out his bag-o-tricks and shared another golden nugget with us.

This time he shares a pattern to simplify Class-style instantiation of a function in JavaScript.

In a nutshell, John takes this example:

function User(first, last){
    this.name = first + " " + last;
}

var user = new User("John", "Resig");

and shows how it can become a debugging nightmare and why it's not as efficient and flexible as other methods. Most importantly, he covers why the use of "this" in a function requires that it be instantiated and not called directly.

Then, he gives us the solution that solves the problems raised in the code above with this example:

function User(first, last){
  if ( this instanceof User ) {
    this.name = first + " " + last;
  } else
    return new User(first, last);
}

Then he wraps this together into a generic class constructor that can be reused to build these types of functions:

// makeClass - By John Resig (MIT Licensed)
function makeClass(){
  return function(args){
    if ( this instanceof arguments.callee ) {
      if ( typeof this.init == "function" )
        this.init.apply( this, args );
    } else
      return new arguments.callee( arguments );
  };
}

Refactoring the original example code at the top of this post with this generic class constructor would produce:

var User = makeClass();
User.prototype.init = function(first, last){
  this.name = first + " " + last;
};
var user = User("John", "Resig");
user.name
// => "John Resig" 

Click here to read John's post in which he does a great job explaining the code above (including the pitfalls of the original example and how the solution works).