Javascript – Why does jQuery use “new jQuery.fn.init()” for creating jQuery object but I can’t

javascriptjqueryoop

I try to create some class based-on jQuery style like the following code.

myClass = window.myClass = function(x, y)
{
    return new myClass.fn.init(x, y);
};

myClass.fn = myClass.prototype = 
{
    init: function(x, y)
    {
        // logic for creating new myClass object.
    }
};

I do not understand why jQuery use new keyword for creating its class because from my experiment, JavaScript always create myClass.init object instead of myClass object. However, I try to remove new keyword in myClass constructor. But it still not changes. Can you explain why jQuery can do that but I can’t or give me some code for using in init function?

By the way, I can use the following code instead of jQuery style code for creating the same object. What is the different between my code & jQuery code? Are there any benefit for using jQuery style?

myClass = window.myClass = function(x, y)
{
    this.init(x, y);
};

myClass.fn = myClass.prototype = 
{
    init: function(x, y)
    {
        this.x = x;
        this.y = y;
    }
};

PS. I like write code that separate initial logic into function because it is very easy to override this function by other people that use my code like my following code.

// override init function of myClass
myClass.fn._old_init = myClass.fn.init;
myClass.fn.init = function()
{
    // logic for doing something before init

    this._old_init();

    // logic for doing something after init
};

Thanks,

Best Answer

This approach should work perfectly. One thing you may be missing is the fact that, using this technique, you're not going to be creating an instance of myClass; you're going to be creating an instance of myClass.prototype.init.

So, any methods defined in myClass.prototype won't be available to the instance. You'll want to make sure that the init's prototype points to myClass's prototype:

myClass.fn.init.prototype = myClass.fn;

FWIW, I don't see any real benefit in this approach. What's wrong with this? -

function myClass(x,y) {

    if ( !(this instanceof myClass) ) {
        return new myClass(x,y);
    }

    // Prepare instance

}

myClass.prototype = { /* Methods */ };

// It can still be overwritten:

var oldMyClass = myClass;

function myClass(x,y) {

    // Hack some stuff here...

    return new oldMyClass(x,y);
}