jQuery's object inheritance and the call() method

jQuery provides a great tool to handle inheritance in OOP: the extend method. With this method, we can actually create a target object that contains all the methods and properties of one or more objects. The basic syntax is as follows:

$.extend(target, object1, object2, objectN);

Let's say that we have the following two classes:

var Class = function() {

    this.message = 'Foo';

    this.method = function() {

var SubClass = function() {

    this.message = 'Hello';

    this.show = function() {


var myClass = new Class();
myClass.method(); // 'Foo'
var mySubClass = new SubClass();
mySubClass.show(); // 'Hello'

So far so good: two objects, two methods, two instances, two results. Everything works as expected. Now let's try to merge these two objects into a third one:

var ThirdClass = function(){};
$.extend(ThirdClass, myClass, mySubClass);

We've created an empty class that will work as our target object to be passed to the extend() method. One important thing to note is that in our particular case we've used class instances as arguments for this method, not class names. In fact, if we don't do this, we get undefined because the resulting object is considered to be empty.

Now we want to call the method of the first original class in order to make it display the property of the second original class. To accomplish this task, we use call:

ThirdClass.method.call(mySubClass); //'Hello'

With this code, we've changed the execution context of our method that now points to the second class. As you can see, jQuery's way of handling inheritance preserves a basic aspect of JavaScript OOP programming.

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.