Understanding jQuery's $.extend(), $.fn, and $.fn.extend()
jQuery provides two methods for plugin development: jQuery.fn.extend() and jQuery.extend().
jQuery.fn is equivalent to jQuery.prototype. This allows for the addition of methods to the prototype chain, which are then available to all instances of the jQuery class.
jQuery.extend(object) adds static methods to the jQuery class. For example:
$.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});
$.min(2, 3); // 2
$.max(4, 5); // 5
The extend method can also merge multiple objects into a target object. For instance:
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
$.extend(settings, options);
// settings now becomes { validate: true, limit: 5, name: "bar" }
jQuery.fn.extend(object) adds methods to the jQuery prototype, making them available to all jQuery instances. For example:
$.fn.extend({
alertWhileClick: function() {
$(this).click(function() {
alert($(this).val());
});
}
});
$("#input1").alertWhileClick();
This enables plugins to be dveeloped by extending the prototype. The distinction between jQuery.extend() and jQuery.fn.extend() lies in whether the methods are static or instance-based.