覆盖jQuery函数

23
有没有办法覆盖jQuery的核心函数? 比如我想在size: function()中添加alert(this.length),而不是在源代码中添加。
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());
}
2个回答

46

你差一点就做到了,需要在旧的 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

为什么这个代码对于 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, arguments); } })(jQuery); - MotionGrafika
用相同的数据函数做了一样的事情...救了我的一天。 - Paflow

1
您可以通过在单独的文件中原型化插件方法而无需修改原始源文件来覆盖插件方法,如下所示:
(function ($) {
    $.ui.draggable.prototype._mouseDrag = function(event, noPropagation) {

         // Your Code
    },

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

现在在这里放置你的逻辑或原始代码,以及你项目中需要的新想法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接