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

Asked

Viewed 577 times

2

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

  • What are they for?
  • How to use them?

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 from 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, just use a new (empty) object 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), going on true as a 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 argument is modified, and the others only contribute properties to it. If there is a true at first, the copy is deep, otherwise it is shallow.

And as for the $.fn.extend? This is only a "shortcut" to add new properties to itself $.fn:

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

(And for those who don’t know, $.fn is where the functions that apply to any jQuery object are defined. Ex.: $(seletor).foo(10, 20) implies that there is a function foo in $.fn.)

3

The $.extend serves to "merge" two or more objects in the first Ex: (taken from http://api.jquery.com/jquery.extend/ )

  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 printing object 1 you have:

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

In this case object 1 (containing apple, banana and cherry) is fused with object 2 (containing banana and orange). Note that when fusing objects the banana is replaced (before it had price and weight now only has price) and the new property (orange) is added.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.