Just so there is no misunderstanding, this question is not about allowing for optional parameters in a JS function.
My question is motiviated by the jQuery parseXML
function, which is defined in jQuery.js
as follows:
// Cross-browser xml parsing
// (xml & tmp used interna开发者_JAVA百科lly)
parseXML: function( data, xml, tmp ) {
...
}
Within the body of the function, the parameters xml
and and tmp
are both assigned before they are used. That means they are being used as local variables, so the function could have been defined like this:
parseXML: function(data) {
var xml, tmp;
...
}
What is the benefit of doing it the first way, other than saving a few characters in the minified version of jQuery.js
?
If we define two functions...
function a ( foo ) { }
function b ( foo, bar, baz ) {}
...they'll report different length
s...
console.log( [a.length, b.length] ); // logs [1, 3]
It's very rare to see this little known feature of javascript used.
But apart from shaving a couple of bytes off the minified file-size, this is the only other reason that I can think of.
In general, you might add unused parameters to a function to conform to some pre-agreed function signature, if you're going to pass this function to another function as a callback or continuation, and the API contract says "I call your callback with these parameters", and you don't need all the parameters to do what you want to do in the callback. (This would apply to any language, not just JavaScript.)
In this specific case, I don't know. How is parseXML used; is it called directly, or used as an argument to other functions which might expect a 3-argument function?
(xml & tmp used internally)
You misunderstand the meaning. They do not mean "internally" within the function. They mean internally within the library. The public API of this function has one parameter (data). The private API of this function has 3 parameters.
This is common throughout jQuery. In general these functions can work with and without side effects. The API without side effects is public and jQuery itself will pass in more parameters to cause side effects that you as a user should not be doing.
精彩评论