JQuery. Extend of jQuery. Fn. Extend of method examples

  • 2020-03-30 02:52:56
  • OfStack

JQuery customizes the methods jquery.extend () and jquery.fn.extend (), where jquery.extend () can create global functions or selectors, and jquery.fn.extend () can create jQuery object methods.

Such as:
 
jQuery.extend({ 
showName : function(name){ 
alert(name) 
} 
}); 
jQuery.showName(" Deep blue "); 

In addition to creating plug-ins, jQuery.extend() can be used to extend jQuery objects.
Such as:
 
var a = { 
name : "blue", 
pass : 123 
} 
var b = { 
name : "red", 
pass : 456, 
age : 1 
} 
var c = jQuery.extend({},a,b); 

C has properties of object a and object b, and since object b is after object a, its name property takes precedence in object c.

The jQuery.extend() method passes a series of options for plug-ins, including default values.
 
function fn(options){ 
var options = jQuery.extend({ //List of default parameter options
name1 : value1, 
name2 : value2, 
name3 : value3 
},options); //Use the function's arguments to override or merge into the default parameter options list
//The body of the function
} 
fn({ name1 : value3, name2 : value2 , name3 : value1 });//Using the new values
fn({ name4 : value3, name5 : value2 });//Add new options by default
fn(); //Leave the default option values

When a new parameter value is passed when the method is called, the default parameter option value is overwritten; otherwise, the default parameter value is used.

Create JQuery object methods using JQuery.fn objects

You can add properties and methods with a jQuery. Fn object, which is actually attached to jQuery. Prototype.

What is fn. If you look at the jQuery code, it's not hard to see.
 
jQuery.fn = jQuery.prototype = { 

   init: function( selector, context ) {//....  

   //...... 

}; 

JQuery. Fn = jQuery. Prototype.

Such as:
 
jQuery.fn.test = function(){ 
alert(" This is a jQuery Object methods !"); 
} 
jQuery("div").click(function(){ 
$(this).test(); //Call the test() method on the current jQuery object
}); 

We can create the jQuery object methods by calling the jquery.fn.extend () method.
 
jQuery.fn.extend({ 
test : function(){ 
return this.each(function(){ 
alert(this.nodeName) 
}); 
} 
}); 
jQuery("body *").click(function(){ 
$(this).test(); //Call the jQuery object method
}); 

In a word :jQuery. Extend is a custom extension to jQuery classes, and jQuery. Fn. Extend is a custom extension to jQuery objects.

Related articles: