What is jquery syntax?

I see this quite often in some jQuery plugins

    $('#foo').myPlugin({
    foo: 'bar',
            bar: 'foo'
});

      

I'm talking about {} in the .myPlugin () part. I often see anonymous functions like

.click(function(){
});

      

but the above syntax looks different

thanks for your help!

+2


a source to share


3 answers


It is an object. This notation is used for named arguments modeling - something that JS cannot do natively AFAIK.

It allows infinite expansion of additional arguments without declaring them in the function declaration:

function myfunc(args)  { }  
vs.
function myfunc(duration, opacity, width, height, speed)  { }

      

and - most importantly - allows arbitrary ordering of arguments:



{"duration": "0.5",
 "width": 300,
 "speed": 2 }

      

Seeing that many JS developers do not work in the context of IDEs (which mapped expected functional parameters using "look-ahead"), this is very convenient, since you do not need to remember the order of the parameter which comes when.

The downside to this is that if there is an IDE, it is very difficult to provide any "forward looking" functionality for these bogus named arguments, and the arbitrary order of the arguments can lead to some chaos in the long run.

+4


a source


It is a JavaScript text object. It is part of the JavaScript language (not jQuery). JavaScript objects are essentially maps of names and values; the name and value are separated by a colon and the pairs are separated by commas. It's all wrapped in a pair of curly braces.

So, if you did something like this:

var obj = { foo: 'bar', name: 'value' };

      

Later on, you can do something like this:



alert(obj.foo); //alerts "bar"

      

or even:

alert(obj['foo']); //also alerts "bar"

      

In this case, the object is passed as a parameter to the myPlugin () function.

+2


a source


It's just a function call, where arg is actually the parameter mapping.

0


a source







All Articles