简体   繁体   中英

In Javascript, what does this syntax mean?

I found this snippet when i was looking at jQuery plugins and wonder what it actually does

A jQuery plugin skeleton:

(function($) {
    ... 
})(jQuery); 

And more recently in nettuts :

var STICKIES = (function () {
    ...
}()); 

This creates a anonymous function and calls it directly: this is equivalent to

var fun = function(){};
fun();

its used in jquery plugins to ensure compatibility with other libraries defining a global variable '$'. in your plugin sekeleton, you wrap your plugin in a anonymous function, which receives an argument named '$' (thus overriding a global variable '$'), this anonymous function is then called with 'jQuery' as parameter, so effectively $ becomes = jQuery, but only within that anonymous function.

The first part:

function($) {
    ... 
}

creates an anonymous function. The second part: wrapping this function with braces and (jQuery); cal the function with jQuery as argument (usable via $ in the function).

nettuts then saves the result of the call in the variable.

第一个功能意味着$被jQuery覆盖,如果在脚本中给'$'赋予了不同的含义,这将很有用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM