开发者

What does this JavaScript/jQuery syntax mean?

What does the following syntax mean?

(function($){
    $.fn.columnize = function(options) {
    ...

What’s function($)?

开发者_运维问答

What’s $.fn. …?


This convention is used when writing plugins to ensure there is no confilict with other Javascript libraries using the $ notation, whilst ensuring the plugin author can still use this notataion:

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

The author is declaring an anonymous function with a single parameter ($), then immediately calling it and passing the jQuery object to it. This ensures the function is called and that everything in it is defined.

A longer notation might be:

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

Although that would create a variable MyDefs in the global namespace. The anonymous function pattern leaves the global namespace empty, avoiding conflicts.


It declares the columnize function as a jQuery plugin allowing you to use it on elements like this $('.someSelector').columnize(). You could read more about plugin authoring here.


It's probably a jQuery extension, which basically pass (jQuery) at the end like

(function($){
    //$ is jQuery here

    //added columnize function to existing jQuery object
    $.fn.columnize = function(options) {

    }

})(jQuery);


I just found this... is it a Proxy Pattern ?

Proxy Pattern

Combining the above knowledge gives you as a JavaScript developer quite a lot of power. One way to combine that is to implement a proxy pattern in JavaScript, enabling the basics of aspect-oriented programming (AOP):

(function() {
  // log all calls to setArray
  var proxied = jQuery.fn.setArray;
  jQuery.fn.setArray = function() {
    console.log(this, arguments);
    return proxied.apply(this, arguments);
  };
})();

The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.


Don't get confused by the $. Actually, $is a valid variable name in JavaScript (as are all variables containing $, source (PDF)).

So, the first line could be rephrased as

(function (someVariable) {

which might look more common. For the rest, yes it is a proxy pattern, and James Wiseman's answer is explaining, what's going on.


function($) {...} defines an anonymous function with a formal parameter named $. $.fn refers to the property named fn of the object referred to by the variable $.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜