what's this jquery syntax?
I see that quite often in some Jquery plugins
$('#foo').myPlugin(开发者_如何学编程{
foo: 'bar',
bar: 'foo'
});
I'm talking about the {} in the .myPlugin() part. I see quite often anonymous functions like
.click(function(){
});
but the above syntax looks different
thanks for your help!
It is an object. This notation is used to simulate named arguments - something that JS can't do natively AFAIK.
It allows for the infinite extension of additional arguments without having to declare them in the function declaration:
function myfunc(args) { }
vs.
function myfunc(duration, opacity, width, height, speed) { }
and - most importantly - it allows for arbitrary ordering of arguments:
{"duration": "0.5",
"width": 300,
"speed": 2 }
Seeing as many JS developers are not working in the context of an IDE (that would display the expected function parameters using "look-ahead"), that is a very convenient thing, as you don't have to memorize the order of which parameter comes when.
The downside of this is that if there is an IDE, it is very hard to provide any "look-ahead" functionality for these fake named arguments, and the arbitrary ordering of arguments can lead to some degree of chaos in the long run.
It's a JavaScript Object literal. It's part of the JavaScript language (not specific to jQuery). JavaScript objects are essentially maps of names and values; the name and the value are separated by a colon, and the pairs are separated from each other by commas. The whole thing is wrapped in a pair of curly braces.
So, if you did something like this:
var obj = { foo: 'bar', name: 'value' };
You could later do something like this:
alert(obj.foo); //alerts "bar"
or even:
alert(obj['foo']); //also alerts "bar"
In this case, the object is being passed as a parameter to the myPlugin() function.
It is just a function call where arg is actually map of params.
精彩评论