我正在尝试将方法添加到具有相同名称(但参数集不同)的jQuery对象作为另一种方法。
到目前为止我得到了什么:
jQuery.fn.insertBefore = function(elem, duration)
{
this.css("display", "none");
this.insertBefore(elem);
this.toggle(duration);
}
但是,此代码(特别是this.insertBefore(where);
行)根据需要调用此函数,而不调用jQuery insertBefore()
函数。为了将这个函数添加到jQuery对象,并让它重载(而不是覆盖)现有函数,我需要做什么?
编辑:解决方案
(function ($)
{
var oldInsertBefore = $.fn.insertBefore;
jQuery.fn.insertBefore = function(elem, duration)
{
if (duration === undefined)
{
oldInsertBefore.call(this, elem);
return;
}
this.css("display", "none");
this.insertBefore(elem);
this.toggle(duration);
}
})(jQuery);
答案 0 :(得分:5)
在覆盖之前备份原始功能。像这样:
(function($){
var oldInsertBefore = $.fn.insertBefore;
jQuery.fn.insertBefore = function(elem, duration)
{
oldInsertBefore.apply(this, arguments);
this.css("display", "none");
this.insertBefore(elem);
this.toggle(duration);
}
})(jQuery);
答案 1 :(得分:3)
您可以使用$.sub()
(function($){
var sub$ = $.sub();
sub$.fn.insertBefore = function(where, duration) {
this.css("display", "none");
this.insertBefore(where);
this.toggle(duration);
}
/* you can use this plugin in this scope or you could also
return sub$ and call the plugin outside */
})(jQuery);
$.sub()
的说明:
创建jQuery的新副本,可以修改其属性和方法,而不会影响原始jQuery对象。
答案 2 :(得分:0)
从技术角度来看,JavaScript不允许您定义具有相同名称但不同参数的单独函数。您只能拥有一个具有相同名称的函数,但它并不关心有多少参数可以通过。上面发布的所有解决方案都利用了这一点,但最终重命名原始函数并调用它。 除非有一个非常好的理由,否则我建议为自定义方法指定一个不同的名称,以免与现有函数冲突。想象一下其他人试图添加到您的代码库而没有意识到标准的jQuery方法被覆盖了。
您自己的方法可以接受任意数量的参数,这些参数可以通过arguments
对象访问。您可以执行arguments.length
之类的操作,或者只检查您的参数是否存在以确定传递了多少/哪些参数,(参见:https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments)。
在制作自定义插件时,只需传入一个选项对象,jQuery就更为标准,如here所述。
你为什么要这样做呢?
答案 3 :(得分:0)
寻找解决方案来克服一些问题,我来到这里,但发现我从不需要任何类型的重载。在自己的 JS 类中使用 jQuery 我有这个代码:
class myClass
{
appendMessage(elementObj, message) {
...
}
appendOrReplaceMessage(elementObj, message) {
let that = this;
let elObj = elementObj;
let msg = message;
if (elementObj.parent().find('span.error').length) {
this.disableNextButton(elementObj);
elementObj.parent().find('span.error').each(function(index, element) {
$(element).hide({
duration: 300,
complete: (function() {
$(element).remove();
that.appendMessage(elObj, msg);
})
})
});
} else {
this.appendMessage(elementObj, message);
}
}
}
此代码中的挑战在于,在 each
函数内部,变量 this
具有不同于外部的含义。所以我不能使用外部类的上下文来调用方法this.appendMessage()
。在方法 appendOrReplaceMessage()
中添加声明后,我可以将外部对象用作 that
,并且声明的变量也都可以在 each
函数内部使用。
这并没有回答问题,但可能显示了一种规避问题的方法。
与问题中的问题相关 一直提到jQuery-function before()
允许使用函数作为回调,而jquery-function { 中没有给出这个选项{1}}。使用正确的函数对于避免过于复杂的代码显然是必不可少的。
所以问题的代码可以这样使用,可能必须进行一些调整才能使其按预期工作:
insertBefore()
除了解释之外,我的第一个代码块可能有助于获取 before((function(index){
this.css("display", "none");
this.insertBefore(elem);
this.toggle(duration);
}));
函数中变量 elem
和 duration
的值。