What could be the reason for overriding a function using jQuery.extend?

I was looking for a suitable way to extend the bootstrap plugin and found this answer: https://stackoverflow.com/a/165778/

What bothers me is the last section - overriding initialization. The code copied below:

// override the old initialization with the new constructor $.fn.modal = $.extend(function(option) { var args = $.makeArray(arguments), option = args.shift(); return this.each(function() { var $this = $(this); var data = $this.data('modal'), options = $.extend({}, _super.defaults, $this.data(), typeof option == 'object' && option); if ( !data ) { $this.data('modal', (data = new Modal(this, options))); } if (typeof option == 'string') { data[option].apply( data, args ); } else if ( options.show ) { data.show.apply( data, args ); } }); }, $.fn.modal); 

I don’t understand why $ .extend is used in this case - is there an effect that I don’t see? If I execute this code:

 var f1 = function(){console.log(1);}; var f2 = function(){console.log(2);}; var f2 = $.extend(f1,f2); f2(); 

then only 1 is printed to the console, and f1 is equal to f2. So it seems that simple assimilation would do,

 $.fn.modal = function(option) {...} 

but maybe I'm missing something ...

+3
jquery extend twitter-bootstrap
Sep 28 '16 at 15:03
source share
1 answer

You need to change this:

 $.fn.modal = $.extend(function(option) { // your code ... }, $.fn.modal); 

for this:

 $.extend($.fn.modal, function(option) { // your code ... }); 

TL DR

$.extend(a, b) copies the contents of b to (changing its contents), and if it repeats, then the property b remains. In addition, it returns the value of a.

So, if you have this:

 hello = { unique_on_hello: 'hola', message: 'hello message' } world = { unique_on_world: 'mundo', message: 'WORLD MESSAGE' } response = $.extend(hello, world) 

The values ​​of each of them will be:

 hello // {unique_on_hello: "hola", message: "WORLD MESSAGE", unique_on_world: "mundo"} world // {unique_on_world: "mundo", message: "WORLD MESSAGE"} response // {unique_on_hello: "hola", message: "WORLD MESSAGE", unique_on_world: "mundo"} 

So, if you f2 = $.extend(f1,f2); match with :

 $.extend(f1, f2) // Copy properties of f2 to f1 f2 = f1 

Source: https://api.jquery.com/jquery.extend/

0
Sep 28 '16 at 15:26
source share



All Articles