Deferred Instantiation

by bradleytrager

JavaScript

var AsyncConstructor = function() {
    var deferred = new $.Deferred();
    setTimeout(deferred.resolve.bind($, this), 500);
    return deferred.promise();
};

var MyClass = function() {
    return AsyncConstructor.call(this);
};

var MyClass2 = function() {
    return AsyncConstructor.call(this);
};

MyClass.prototype.init = function() {
    console.log("hello");  
};

MyClass2.prototype.init = function() {
    console.log("hello2");  
};

new MyClass().then(function(myInstance) {
    console.log(myInstance);
    myInstance.init();
});

new MyClass2().then(function(myInstance) {
    console.log(myInstance);
    myInstance.init();
});