4

I try to inherit in the following way:

function inherits(ctor, base_ctor){
    ctor.base = base_ctor;
    ctor.prototype = Object.create(base_ctor.prototype, {
        constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true,
        }
    });
}
function MyClass(){
    jQuery.fn.init.call(this,'<form>...</form>');
    //...
}
inherits(MyClass, jQuery);
//...
var $my_obj = new MyClass()

and when I try to

$my_obj.find('#id')

it calls constructor of MyClass again (through function jQuery.fn.pushStack())

How to avoid a recursion?
Or how to inherit (not to extend) from jQuery?

  • Why do you want to inherit from jQuery? There shouldn't be any need to do so. If you need the dollar sign back, use [`jQuery.noConflict()`](https://api.jquery.com/jquery.noconflict/). – Heretic Monkey Feb 22 '16 at 22:22
  • 2
    Have a look [here](http://stackoverflow.com/a/19759103/1048572). However I'd think that's a bad idea. – Bergi Feb 22 '16 at 22:25

1 Answers1

0

For such purpose jQuery provide function jQuery.sub(), and then you may extend copy of jQuery by any methods, but [FIXME] you may not use your own constructor.

Also you may use the following hack:

function MyClass(){
    if(this.property_that_can_not_be_created_by_jQuery)
        return jQuery.apply(this,arguments); // do not use jQuery.fn.init
    this.property_that_can_not_be_created_by_jQuery = true;

    jQuery.fn.init.call(this,'<form>...</form>');
    //...
}
inherits(MyClass, jQuery);

but note, that pushStack() and any functions, that use pushStack() (for example appendTo() and insertAfter()) will return new object created by jQuery's cunstructor and, if you want to get object, that was constructed by your constructor, you shoud use method end()