如何从jQuery继承

菲莉亚·乌斯科夫(Filya Uskov)

我尝试通过以下方式继承:

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()

当我尝试

$my_obj.find('#id')

它再次调用MyClass的构造函数(通过jQuery.fn.pushStack()函数)

如何避免递归?
或者如何从jQuery继承(而不是扩展)?

菲莉亚·乌斯科夫(Filya Uskov)

为此,jQuery提供函数jQuery.sub(),然后您可以通过任何方法扩展jQuery的副本,但是[FIXME]您不能使用自己的构造函数。

您也可以使用以下技巧:

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()

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章