javascript - JQuery UI继承多态

标签 javascript jquery-ui inheritance widget polymorphism

有没有办法在 jQuery UI 中的小部件继承中具有多态性?

例如我想做这样的事情:

$.widget('tr.fatherClass', {
  getValue: function() {
    return null;
  }
  ...
});
// sonClass1: extends from the father
$.widget('tr.sonClass1', $.tr.fatherClass, {
  getValue: function() {
    return this._fooFunction1();
  }
  ...
});
// sonClass2: extends from the father
$.widget('tr.sonClass2', $.tr.fatherClass, {
  getValue: function() {
    return this._fooFunction2();//
  }
  ...
});
// create an instance of a "sonClass"
$('#foo1').sonClass1(options);  
$('#foo2').sonClass2(options);  

然后我想在不知道子类名称的情况下使用“getValue”方法:

$('#foo1').fatherClass('getValue'); // run _fooFunction1() of sonClass1
$('#foo2').fatherClass('getValue'); // run _fooFunction2() of sonClass2

但这是不可能的:

jquery.js:250 Uncaught Error: cannot call methods on variable prior to initialization; attempted to call method 'getValue'

在 JQuery 论坛中,Scott Gonzalez 解释说“创建一个小部件只会创建一个小部件,而不是原型(prototype)链中的每个小部件link

是否有任何变通方法或解决方案可以优雅地执行此操作?

最佳答案

在 OOD 中,支持组合而不是继承很重要。但是如果你仍然想要多态性,而不是切换插件,你可以创建一个函数作为插件变量,你可以在你的应用程序逻辑中覆盖

例子:

$.widget('myWidget', {
    getValue: function() {
      if(userfunc != null)
         return userfunc();
      return null;
   }
   userfunc: null
  });

然后你可以为userfunc创建不同的版本

userfunc1 = function(){  return 43; }
userfunc2 = function(){  return 38; }

$('#foo').myWidget({userfunc : userfunc1})
value = $('#foo').myWidget('getValue') <= returns 47

$('#foo').myWidget({userfunc : userfunc2})
value = $('#foo').myWidget('getValue') <= returns 38

希望对你有帮助

关于javascript - JQuery UI继承多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38125872/

相关文章:

Javascript替换方法避免复制粘贴

javascript - 使用 JXA 移动创建的文件

javascript - jQuery UI 选择——帮助解决低效问题

python - 如果派生类中的属性被覆盖,如何调用基类的数据成员?

C++ 非多态接口(interface)

c++ - C++中Parents成员变量的继承?

javascript - 将 Livecycle 动态可填写 PDF 转换为静态可填写 PDF(而不是扁平化 PDF)

javascript - jquery ajax无法循环遍历找到的数据

javascript - ajax给出html和脚本

jquery位置函数/对象