Search code examples
javascriptjqueryprototypejquery-select2jquery-select2-4

What is the Javascript feature that is behind select2


To turn a normal Html select into a select2 the documentation says to simply call select2() on the normal Html select like this

$(document).ready(function() {
    $('.js-example-basic-single').select2();
});

When I tried this out, I also imported the select2 module that I installed via npm.

import select2 from 'select2';

What is name of the Javascript feature / concept / technology that allows one to add a new function (in this case .select2()) to an existing object?


Update I forgot to mention that I'm using jquery which is what BJRINT picked up. So it seems this is a jquery + select2 thing.


Solution

  • What is name of the Javascript feature that allows one to add a new function to an existing object?

    Short answer:

    Prototypes.

    Prototypes are the mechanism by which JavaScript objects inherit features from one another. The prototype property can be used to add methods to existing constructors.

    For more details about JavaScript prototype, you can refer to MDN documentation on Object prototypes.


    Detailed answer:

    • select2 is a jQuery plugin. If you inspect it's source code, you'll find that it extends $.fn with a new function called select2:
    $.fn.select2 = function (options) {..}
    

    • If you inspect jQuery's source code, you'll find that jQuery.fn is an alias of jQuery.prototype:
    jQuery.fn = jQuery.prototype = { ... }
    


    • And, also in jQuery's source code, you can find that the global variable '$' is an alias for the jQuery object:
    window.jQuery = window.$ = jQuery;
    

    So, basically...

    • $ is an alias for the jQuery() function
    • $('.js-example-basic-single') returns a jQuery object
    • Your plugin has extended this jQuery object with a new method select2()