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,