How to design a JavaScript class to support callbacks in a clean way?
<p>I've tried to design some classes to support a callback functionality. Classes MyClass1 and MyClass2 didn't work. Class3 worked, but the design is really horrible. It uses a external class reference to call the method. I'd like to implement a design similar to MyClass1, which is a lot clearer and isn't coupled to an external variable. This callback mechanism would really be great to ajax calls too.
$j is just an alias to jQuery.</p>

<pre><code>function MyClass1() {  
    $j("#myDiv1").click(this.func);

    this.func = function() {
        alert("Inside method.");
    }
}

var _class2;  
function MyClass2() {  
    _class2 = this;  
    $j("#myDiv2").click( _class2.func );

    this.func = function() {
        alert("Inside method.");
    }
}

function MyClass3() {  
    $j("#myDiv3").click( function() { cls3.func(); } );   

    this.func = function() {
        alert("Inside method.");
    }
}

var cls1 = new MyClass1();  
var cls2 = new MyClass2();  
var cls3 = new MyClass3();  
</code></pre>
