【问题标题】:Javascript Inheritance - this.element is undefined in subclassJavascript 继承 - this.element 在子类中未定义
【发布时间】:2011-10-28 16:31:14
【问题描述】:

我正在尝试设置一个扩展子类的父类,但是当我从超类调用时尝试在子类中引用 this.element 时,它是未定义的。我在这里做错了什么?

$.widget("ui.testSuper", $.extend({}, $.ui.testSub.prototype, 
{
    _init: function ()
    {
        $.ui.testSub.prototype._init();
    },
...
}));

$.widget("ui.testSub", $.ui.mouse,
{
    _init: function ()
    {
        this.element.addClass("some-class");
    },
...
});

$('#some-element').testSub({ }); // this works fine

$('#some-element').testSuper({ }); // this.element is undefined

【问题讨论】:

  • 可能是因为 jQuery 在某处做了黑魔法。

标签: javascript jquery inheritance


【解决方案1】:

当您扩展 $.ui.testSub 时,它在那个时候并不存在。您需要做的就是交换这两个代码块:

//Should be first
$.widget("ui.testSub", $.ui.mouse,
{
    _init: function ()
    {
        this.element.addClass("some-class");
    },
...
});

$.widget("ui.testSuper", $.extend({}, $.ui.testSub.prototype, 
{
    _init: function ()
    {
        $.ui.testSub.prototype._init();
    },
...
}));

$('#some-element').testSub({ }); // this works fine

$('#some-element').testSuper({ }); // then it will work fine as well

查看实时示例here

更新

我明白你在说什么。您需要像这样调用基本方法

$.ui.testSub.prototype._init.call(this);

因此您不会丢失元素的上下文。例如here

【讨论】:

  • 订购的有效点,我在发布问题时没有考虑到这一点。但根本问题仍然存在 - 如果您实际添加我试图调用小部件的元素,您可以看到它。 jsfiddle.net/46D8T/12
【解决方案2】:

我不确定使用 $.extend 是否适合这里。

这是我通常扩展 jQuery UI 小部件的方式:

$.widget('ui.testSuper', $.ui.testSub {
    _create: function() {
        $.ui.testSub.prototype._create.call(this);
    }
});

我看到你正在使用 _init,所以必须使用旧版本的 jQuery UI。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多