jQuery extend: Explained with 3 examples


jQuery extend: Explained with 3 examples

jQuery extend: Explained with 3 examples

jQuery extend

In Object Oriented Programming (OOP), the extend is one of the major concepts to understand that relates to inheritance. Inheritance is a concept that allows extending the built classes. i.e. The work that has been done by one programmer can be not only reused by others but other programmers can extend its functionality.

In jQuery, extend works almost like that where you “inherit” object, functionality. You can extend a plugin developed by a programmer or company, for example, keeping its existing functionality as well as adding new features to it.

See an example of extend

Similarly, you can extend objects. Suppose a feedback form is built by a jQuery developer that has fields: Name, Email, Feedback. Now you want to add more fields like address, website etc. to that existing form. You can inherit that form that will have Name, Email, Feedback options plus you add address and website fields as well to that form.

The extend allows you to do that.

Below you can see the basic example of using jQuery extend, for demonstration purpose.

Basic example of using extend jQuery

The example below creates three object variables. Object1 containing name and age. Object2 contains profession while object3, which is the target object is kept blank in the start.

By using extend, object3 will take object1 and object2 “content”. As you click on button “Click to see Object3”, it will show three variables taken from object1 and object2.

jQuery extend

Experience this example online



Adding variables to target object

This example adds variable to target object3 while extend method merges object1 and object2 into object3 as well.

Experience this example online



Example of before and after using extent method

To make it easier look at this example. As you click on the first button “Object3 before extend”, the first div will be filled with Object3 before using the jQuery extend method.

As you click on the second button “Object3 after extend” it will show merged object3 after extend.

jQuery extend before after

Experience this example online



 

Related reading: jQuery class | jQuery remove class



Was this article helpful?