【问题标题】:Override jQuery functions覆盖 jQuery 函数
【发布时间】:2011-05-31 00:33:47
【问题描述】:

有没有办法覆盖 jQuery 的核心功能? 假设我想添加一个警报(this.length)大小:function() 而不是在源代码中添加它

size: function() {
    alert(this.length)
    return this.length;
},

我想知道是否可以做这样的事情:

if (console)
{
    console.log("Size of div = " + $("div").size());
    var oSize = jQuery.fn.size;
    jQuery.fn.size = function()
    {
        alert(this.length);

        // Now go back to jQuery's original size()
        return oSize(this);        
    }
    console.log("Size of div = " + $("div").size());
}

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    几乎拥有它,您需要将旧 size 函数内的 this 引用设置为覆盖函数中的 this 引用,如下所示:

    var oSize = jQuery.fn.size;
    jQuery.fn.size = function() {
        alert(this.length);
    
        // Now go back to jQuery's original size()
        return oSize.apply(this, arguments);
    };
    

    其工作方式是Function 实例有一个名为apply 的方法,其目的是任意覆盖函数体内的内部this 引用。

    所以,举个例子:

    var f = function() { console.log(this); }
    f.apply("Hello World", null); //prints "Hello World" to the console
    

    【讨论】:

    • @Gabriel 感谢您的链接! :)
    • 这对 init 不起作用有什么特别的原因吗? (function($) { var _o_init = jQuery.fn.init; jQuery.fn.init = function(selector, context) { if (console) console.log("Function Call : init"); return _o_init.apply(this , 参数); } })(jQuery);
    • 对数据函数做了同样的事情..拯救了我的一天
    【解决方案2】:

    您可以通过在单独的文件中对其进行原型化来覆盖插件方法,而无需修改原始源文件,如下所示::

    (function ($) {
        $.ui.draggable.prototype._mouseDrag = function(event, noPropagation) {
    
             // Your Code
        },
    
        $.ui.resizable.prototype._mouseDrag = function(event) {
                // Your code
        }   
    }(jQuery));
    

    现在将您的逻辑或带有项目所需的新想法的原始代码放在这里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2013-06-07
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多