Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"Someone pointed out though, that you can prevent this polluting of the namespace (those are just big words for creating global variables) by using this trick:

     function Person(name){
        if (!(this instanceof Person))
            return new Person(name)
        this.name = name
     }"
This is useful for situations where you might want to be able to create anonymous objects and call a series of methods on them, which can be a nice API as any user of jQuery knows.

It's also an arguably cleaner way of achieving the constructor+apply thing he does later -- no global modification of the Function prototype.

A lot of the time, though, I'll just consider this my default "class" definition:

    function Person (args) { this.init(args); }
If you want to be warned (or want others to be warned) when Person is called w/o new, this will do it (unless someone has defined init on the global namespace, so avoid that).

This also makes it easier to hand around the method that does the actual construction, which is helpful for cases like constructor + apply:

    var p = new Person;
    p.init.apply(p,args);
(again, without global modification of the Function prototype) or for cases where you want to refer to "superclass" methods down an inheritance hierarchy.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: