如何在jQuery中向现有扩展函数添加方法?

时间:2012-09-27 20:40:31

标签: jquery

如何在jQuery中扩展现有的对象方法?

例如,我正在使用jqBarGraph。现在我想为它添加一个addGrid()函数。我以为我会这样做:

(function($) {
  $.fn.jqBarGraph.addGrid = function(){
    var o = this;
    // do something with 'o'
    return o;
  }
})(jQuery);

...但是当我致电$('#chart').jqBarGraph(options).addGrid();时 - 我收到错误:

Uncaught TypeError: Cannot call method 'addGrid' of undefined

1 个答案:

答案 0 :(得分:6)

您正在为该函数添加一个属性,因此您实际上只能访问它。例如。

$('#chart').jqBarGraph.addGrid();

这不是你想要的。似乎jqBarGraph在调用时不会返回任何内容。你必须自己修补这个功能:

(function(old) {
  $.fn.jqBarGraph = function() {
    old.apply(this, arguments);  // call the actual function

    // return something
    return {
      addGraph: function() { ... }
    };
  };

  $.fn.jqBarGraph.defaults = old.defaults;  // restore properties
})($.fn.jqBarGraph);
相关问题