【问题标题】:How to inherit from jQuery如何从 jQuery 继承
【发布时间】:2016-06-04 10:33:16
【问题描述】:

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

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继承(而不是扩展)?

【问题讨论】:

  • 为什么要继承自jQuery?应该没有必要这样做。如果您需要美元符号,请使用jQuery.noConflict()
  • 看看here。但是我认为这是个坏主意。

标签: javascript jquery inheritance


【解决方案1】:

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

您还可以使用以下 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()

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多