How to inherit from jQuery

I am trying to inherit as follows:

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

$my_obj.find('#id')

it calls the MyClass constructor again (via the jQuery.fn.pushStack () function)

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

+4
source share
1 answer

JQuery provides the jQuery.sub () function for this purpose , and then you can distribute a copy of jQuery by any methods, but [FIXME] you cannot use your own constructor.

You can also 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);

, pushStack() , pushStack() (, appendTo() insertAfter()), , jQuery cunstructor, , , , end()

0

Source: https://habr.com/ru/post/1629947/


All Articles