I am a javascript newbie and recently came into the following code.
(function($){
if(!document.defaultView || !document.defaultView.getComputedStyle){
var oldCurCSS = jQuery.curCSS;
jQuery.curCSS = function(elem, name, force){
if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
return oldCurCSS.apply(this, arguments);
}
var style = elem.style;
if ( !force && style && style[ name ] ){
return style[ name ];
}
return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
};
}
})(jQuery);
What is function($) {...} (jQuery)?
PS: I also don't quite get what the code is for... If possible please give a hint on it.
It's a self-executing anonoymous function called with jQuery as argument, that gets renamed to $ inside the function signature.
Since you don't know if jQuery.noConflict() has been used in the page (especially if you are writing distributable code like Plugins), this way you can use the shorthand $ inside your function safely.
Who wrote it is actually stupid beacuse he's using jQuery inside the function anyway : )
It also prevents the variables from polluting the global namespace and encapsulates them making them unaccessible from outside the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With