Javascript: Callback in constructor

design-patterns, javascript

Solution

It should be a simple fix. First, make sure your callback is called with the `this` object set to the current object

function foo(callback) {
    // do slow initialization here..

    callback.call(this);
};

Then adjust how you make your callback

var f = new foo(function() {
    this.doStuff();
});​

Here's your updated fiddle

Problem

I'm trying to write OO javascript for an object that has an expensive initialization process that will callback a function when its done. The problem is that the caller needs to use the functions of that same object in the callback routine, and the object doesn't exist yet: ``` // ctor for foo object function foo(callback) { // do slow initialization here.. // callback when done callback(); }; foo.prototype = function() { return { // doStuff method doStuff: function() { alert('stuff done'); } }; }(); // instantiate the foo object, passing in the callback var f = new foo(function() { //Uncaught TypeError: Cannot call method 'doStuff' of undefined f.doStuff(); });​ ``` jsFiddle What am I missing here?

Original source