jQuery has customized jQuery.extend() and jQuery.fn.extend() methods. The jQuery.extend() method can create global functions or selectors, and the jQuery.fn.extend() method can create jQuery object methods.
For example:
jQuery.extend({
showName : function(name){
alert(name)
}
});
jQuery.showName("Dark Blue");
jQuery. In addition to creating plug-ins, extend() can also be used to extend jQuery objects.
For example:
var a = {
name : "blue",
pass : 123
}
var b = {
name : "red",
pass : 456,
age : 1
}
var c = jQuery.extend({},a,b);
c owns a,b objects Attributes, since the b object is after the a object, its name attribute is first in the c object.
The jQuery.extend() method passes a series of options to the plug-in, including the default value.
function fn(options){
var options = jQuery.extend({ //Default Parameter option list
name1: value1,
name2: value2,
name3: value3
},options); //Use function parameters to overwrite or merge into the default parameter option list
/ /Function body
}
fn({ name1 : value3, name2 : value2 , name3 : value1 });//Use new value
fn({ name4 : value3, name5 : value2 });// Add new options to the default
fn(); //Keep the default option values
When this method is called, passing new parameter values will overwrite the default parameter option values. , otherwise, use the default parameter value.
Use JQuery.fn object to create JQuery object method
You can add properties and methods through jQuery.fn object. In fact, jQuery.fn object is a hook On jQuery.prototype, jQuery abbreviates it. What is
fn. Looking at the jQuery code, it's not hard to find.
jQuery.fn = jQuery.prototype = {
init: function(selector, context) {//....
//……
};
Original jQuery.fn = jQuery.prototype. You are definitely familiar with prototype.
For example:
jQuery.fn. test = function(){
alert("This is a jQuery object method!");
}
jQuery("div").click(function(){
$(this).test (); //Call the test() method on the current jQuery object
});
We can call the jQuery.fn.extend() method to create a jQuery object method.
jQuery.fn.extend({
test : function( ){
return this.each(function(){
alert(this.nodeName)
});
}
});
jQuery("body *"). click(function(){
$(this).test(); //Call jQuery object method
});
In a word: jQuery.extend is for the JQuery class Custom extension, jQuery.fn.extend is a custom extension to the JQuery object.