Function overloading in jQuery object

I am trying to add a method to a jQuery object with the same name (but with a different set of parameters) as another method.

What I have so far:

jQuery.fn.insertBefore = function(elem, duration) { this.css("display", "none"); this.insertBefore(elem); this.toggle(duration); } 

However, this code (in particular, the line this.insertBefore(where); ) calls the same function, not the jQuery insertBefore() function, at will. What do I need to do to add this function to the jQuery object and reload (not overwrite) the existing one function?

EDIT: solution

 (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); 
+4
source share
3 answers

You retain the original function before dubbing. Something like that:

 (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); 
+5
source

you can use $.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); 

description of $.sub() :

Creates a new copy of jQuery, the properties and methods of which can be changed without affecting the original jQuery object.

from http://api.jquery.com/jQuery.sub/

+3
source

From a technical point of view, JavaScript does not allow you to define individual functions with the same name, but different arguments. You can only have one function with the same name, although it doesn't matter how many arguments come in. All of the above solutions use this, but simply rename the original function and call it. If you have a really good reason, I suggest giving your custom method a different name so that it does not conflict with an existing function. Imagine that someone else is trying to add code to your database and does not understand that the standard jQuery method has been overwritten.

Your own method can accept any number of arguments that can be accessed through the arguments object. You can do things like arguments.length or just check if your arguments exist to find out how many / which arguments were passed (see https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments )

In jQuery, it is more standard to simply pass an options object when creating a custom plugin, as described here .

Why are you trying to do this for sure?

0
source

Source: https://habr.com/ru/post/1388158/


All Articles