如何在jQuery中扩展现有的对象方法?
例如,我正在使用jqBarGraph.现在我想addGrid()为它添加一个函数.我以为我会这样做:
(function($) {
$.fn.jqBarGraph.addGrid = function(){
var o = this;
// do something with 'o'
return o;
}
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
...但是当我打电话时$('#chart').jqBarGraph(options).addGrid();- 我收到错误:
Uncaught TypeError: Cannot call method 'addGrid' of undefined
您正在为该函数添加一个属性,因此您实际上只能访问它,例如
$('#chart').jqBarGraph.addGrid();
Run Code Online (Sandbox Code Playgroud)
这不是你想要的.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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |