Factory/Constructor

By Luke Smith on March 17, 2008 11:06 PM

In JavasScript, functions are defacto constructors. When called with new, the this will refer to the newly created instance. However, when called as a function, this will refer to the scope from which it was called (a namespace object or possibly window).

So here's a way to make either approach return an instance:

var MyClass = function (cf) {
    if (!(this instanceof arguments.callee)) {
        return new arguments.callee(cf);
    }

    /* Constructor stuff here */
};

Using this type of function body will allow you to treat the function as an instance constructor

var foo = new MyClass(blah);

or a factory method

var foo = MyClass(blah);

No TrackBacks (http://lucassmith.name/mt/mt-tb.cgi/103)

ls.n

LucasSmith.name

Luke and Heidi

I'm Luke. I am a front end engineer at Yahoo! on the YUI team.

Mostly I write about code stuff, but occassionally I'll mix in some real life. You've been warned.

Archives

Tags

Feeds

Subscribe to feed Recent entries

Content licensed under Creative Commons

Code licensed under BSD license

©2005 - 2010 Lucas Smith

Powered by Movable Type