What is '$ .extend' and '$ .fn.extend' for?

2

jQuery has the functions $.extend and $.fn.extend .

  • What are they for?
  • How to use them?
asked by anonymous 04.08.2014 / 15:37

2 answers

5

The function of extend is to copy properties of one or more objects to a target object. That is, it is a utilitarian function, which acts on "normal" objects, nothing specific to jQuery.

var a = { foo:10 };
var b = { bar:20 };
$.extends(a, b);
// a agora possui { foo:10, bar:20 }

One of its most common uses is to clone an object. To do this, simply use a new object (empty) as the first argument:

var a = { foo:10, bar:[20, 30, 40] };
var b = $.extend({}, a); // Cópia rasa (shallow copy)

a.bar[1] = 50;
console.log(b.bar[1]); // 50

Or, to get a "deep copy" ( deep copy ), passing true as the first argument:

var a = { foo:10, bar:[20, 30, 40] };
var b = $.extend(true, {}, a); // Cópia profunda (deep copy)

a.bar[1] = 50;
console.log(b.bar[1]); // 30

Another possibility is to create an object that is a set of several others. This can be used, for example, to implement mixins :

var classeA = { ... }; // Uma "classe" no caso é somente um conjunto de propriedades
var classeB = { ... }; // e métodos relacionados. Poderia-se "herdar" dessa classe
var classeC = { ... }; // usando-a como protótipo, mas como herdar de várias?

var mixin = $.extend({}, classeA, classeB, classeC);

As a general rule, the first object passed as an argument is modified, and the others only contribute properties to it. If there is a true at the beginning, the copy is deep, otherwise it is shallow.

What about $.fn.extend ? This is just a "shortcut" to adding new properties to $.fn itself:

$.fn.extend({ ... }, { ... }, ...);
// É equivalente a:
$.extend($.fn, { ... }, { ... }, ...);

(And for those who do not know, $.fn is where you define the functions that apply to any jQuery object.): $(seletor).foo(10, 20) implies that there is a foo function in $.fn .)

    
04.08.2014 / 19:56
2

The $.extend serves to "merge" two or more objects in the first Ex: (removed from link )

  var object1 = {
      maça: 0,
      banana: { peso: 52, preço: 100 },
      cereja: 97
    };
    var object2 = {
      banana: { preço: 200 },
      laranja: 100
    };

  $.extend( object1, object2 );

When you print object 1, you have:

{"maça"0, "banana":{preço:200}, cereja:97, laranja:100}

In this case, object 1 (which contains mace, banana and cherry) is fused with object 2 (which contains banana and orange). Note that in merging the objects the banana is replaced (previously it had price and weight now only has price) and the new property (orange) is added.

    
04.08.2014 / 16:11