I'd like to understand the jQuery plugin syntax

前端 未结 7 1028
遇见更好的自我
遇见更好的自我 2020-11-28 18:39

The jQuery site lists the basic plugin syntax for jQuery as this:

(function( $ ){    
  $.fn.myPlugin = function() {      
    // there\'s no need to do $(th         


        
7条回答
  •  春和景丽
    2020-11-28 19:04

    The basic plugin syntax allows you to use $ to refer to jQuery in the body of your plugin, regardless of the identify of $ at the time the plugin is loaded. This prevents naming conflicts with other libraries, most notably Prototype.

    The syntax defines a function that accepts a parameter known as $ so you can refer to it as $ in the function body, and then immediately invokes that function, putting jQuery in as the argument.

    This also helps not pollute the global namespace (so declaring var myvar = 123; in your plugin body won't suddenly define window.myvar), but the main ostensible purpose is to allow you to use $ where $ may have since been redefined.

提交回复
热议问题