jleck
jleck

Reputation: 861

Extending $.fn.init function

I'm trying to extend jQuery with the following:

$.fn.extend({
    initCore:   $.fn.init,
    init:       function (selector, context, rootjQuery) {
        return $.fn.initCore(selector, context, rootjQuery);
    }
}),

However, it doesn't seem to work right, and creating simple things such as an alert on click produce errors. Can anyone spot the problem?

Thanks in advance!

Upvotes: 2

Views: 980

Answers (3)

oyosoftware
oyosoftware

Reputation: 21

At first, the last comma doesn't belong there. Secondly, you only have to add the new keyword to the code:

$.fn.extend({
    initCore:   $.fn.init,
    init: function (selector, context, rootjQuery) {
        return new $.fn.initCore(selector, context, rootjQuery);
    }
})

Reason: initCore is the constructor, and you can't return a constructor as an object. You have to create an object from the constructor.

Upvotes: 0

Bergi
Bergi

Reputation: 664538

I guess you're missing the context. Try

return $.fn.initCore.call(this, selector, context, rootjQuery);

or even easier

return this.initCore(selector, context, rootjQuery);

No, wait, init is the constructor itself. That means

$.fn.initCore.call(this, selector, context, rootjQuery);
doSomeThingWith(this);

...

$.fn.init.prototype = $.fn;

or

var ob = new $.fn.initCore(selector, context, rootjQuery);
doSomeThingWith(ob);
return ob;

Upvotes: 1

SLaks
SLaks

Reputation: 887453

$.fn.init is the class constructor itself.

Try adding $.fn.init.prototype = $.fn afterwords to restore the original prototype.

Upvotes: 4

Related Questions