Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding jQuery's $.extend(), $.fn, and $.fn.extend()

Tech Apr 28 19

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.