覆盖jQuery函数 [英] Override jQuery functions

查看:116
本文介绍了覆盖jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


推荐答案

几乎有了它,你需要在旧的 size 函数中设置这个引用为<$覆盖函数中的c $ c> this 引用,如下所示:

You almost had it, you need to set the this reference inside of the old size function to be the this reference in the override function, like 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);
};

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

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

所以,举个例子:

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

这篇关于覆盖jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆