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).

javascript is more difficult than java!!!!

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <div> <blockquote> <object> <embed> <img> <param>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Copy the characters (respecting upper/lower case) from the image.