jQuery: extending object instances

The jQuery's $.extend() is often used with object literals to extend them, thus creating a resulting object by merging other objects together. However, the power of this method goes well beyond object literals and encompass also object instances of traditional objects which make use of the new operator. For example, having these two objects:

var ClassA = function() {

  this.property = 'Test 1';


var ClassB = function() {

  this.test = 'Test 2';


Here we have two traditional objects that can be instantiated using the new operator. $.extend() works with the prototype object of JavaScript objects, so we have to instantiate them first:

var a = new ClassA();
var b = new ClassB();

Once the instances have been created, we can pass them to $.extend() to generate a third object:

var ClassC = $.extend(a, b);

Testing them everything works as expected:

$.each(ClassC, function(index, item) {
    alert(index + ': ' + item); // property: 'Test 1', test: 'Test 2'

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.