覆盖jQuery函数 [英] Override jQuery functions
问题描述
有没有办法覆盖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屋!