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
Override jQuery functions
提问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 this
reference inside of the old size
function to be the this
reference 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 Function
instances have a method called apply
, whose purpose is to arbitrarily override the inner this
reference 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.
现在将您的逻辑或原始代码与您的项目所需的新想法放在一起。