JavaScript: object instance getters

I'm basically a developer with a classical, traditional OOP background, so when it comes to JavaScript, I just keep banging my head on the desk because many things that I take for granted are not so easy in JavaScript. In other words, they need a little bit of language introspection to get to the point. I mean, JavaScript is a Jedi Master language, so beautiful, so powerful but, ouch, also so puzzling.

Take PHP for example: you have self and... voilà, here's your object instance. Further, you can even use $this and you're done. With all these ideas which crowded my mind, I basically tried this:

function Class() {
    var self = this;
    this.getInstance = function() {
        return new self();
    }
    this.method = function() {
        alert('Method');
    }
}

var myClass = new Class();
myClass.method(); // alerts 'Method'

var instance = myClass.getInstance();
instance.method(); // ERROR: 'this' is not a constructor

Yeah, a constructor. In JavaScript, objects, methods and classes are functions, so we need a function here. I banged my head on the desk for a while, looked through my messy code and then:

var self = Class;

That was so obvious that I felt a little stupid. Dear reader, maybe I am.

Leave a Reply

Note: Only a member of this blog may post a comment.