Tip about jQuery $.extend

What is $.extend?

A little info:

$.extend is an object merger. Its arguments are target and objects.

Example:

$.extend({ guy: ‘policeman’ }, { truncheon: ‘big’ }, { gun: ’small’ })

Returns:

{guy: ‘policeman’, truncheon: ‘big’, gun: ’small’} - merged in one

What if derive classes?

In official documentation for this method I did’not find an example for use to create derived classes. So I tried, $.extend prototypes of two objects.

For example:

var Man = function(){}
Man.prototype = {
     go: function(where){}
}
 
var Policeman = function(){}
Policeman.prototype = $.extend(Man.prototype, {
     kick: function(who){},
     go: function() {// very seriously, policeman not dance when walk}
});
 
Grandpa.prototype = $.extend(Man.prototype, {
     go: function() {// walk with stick}
});

Everything worked normal for Policeman, but when I tried to make Grandpa derived class, one more from Man, I found wired things. And after all I understood, that $.extend returns, not new object, with all, but returns target merged with other, so when I use another time the same target, it would be Policeman already. And my Grandpa became man who walk with stick and kick asses for bad guys))

Solution

Use empty objects as targets {}, see below.

Grandpa.prototype = $.extend({}, Man.prototype, {
     go: function() {// walk with stick}
});

kick it on DotNetKicks.com

Tags: ,

One Response to “Tip about jQuery $.extend”

  1. WebDevVote Says:

    You’re been voted!
    Track back from http://webdevvote.com

Leave a Reply