Javascript 覆盖 jQuery 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4536788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:49:12  来源:igfitidea点击:

Override jQuery functions

javascriptjquery

提问by MotionGrafika

Is there way to override jQuery's core functions ? Say I wanted to add an alert(this.length) in size: function() Instead of adding it in the source

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

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

I was wondering if it would be possible to do something like this :

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

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());
}

回答by Jacob Relkin

You almosthad it, you need to set the thisreference inside of the old sizefunction to be the thisreference in the override function, like this:

几乎拥有它,您需要this将旧size函数内部的引用设置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);
};

The way this works is Functioninstances have a method called apply, whose purpose is to arbitrarily override the inner thisreference inside of the function's body.

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

So, as an example:

所以,作为一个例子:

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

回答by Lalit Kumar

You can override plugins method by prototype it in a separate file without modifying original source file as below::

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

(function ($) {
    $.ui.draggable.prototype._mouseDrag = function(event, noPropagation) {

         // Your Code
    },

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

Now put your logic here or original code with your new idea that is needed in your project.

现在将您的逻辑或原始代码与您的项目所需的新想法放在一起。