Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 重写jQuery函数_Javascript_Jquery - Fatal编程技术网

Javascript 重写jQuery函数

Javascript 重写jQuery函数,javascript,jquery,Javascript,Jquery,有没有办法覆盖jQuery的核心功能? 假设我想在size:function()中添加一个警报(this.length) 而不是将其添加到源中 size: function() { alert(this.length) return this.length; }, 我想知道是否可以这样做: if (console) { console.log("Size of div = " + $("div").size()); var oSize = jQuery.fn.s

有没有办法覆盖jQuery的核心功能? 假设我想在size:function()中添加一个警报(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());
}
您几乎拥有了它,您需要将旧
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);
};
其工作方式是
函数
实例有一个名为
应用
的方法,其目的是任意重写函数体内部的
引用

例如:

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

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

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

         // Your Code
    },

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

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

@Gabriel感谢您的链接!:)有没有什么特别的原因可以解释为什么init不起作用?(function($){var\u 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);对数据函数也做了同样的操作。。救了我一天