Redeclaring function parameters as variables?
I can't seem to find an answer for this anywhere on the 'Net...
Is there any reason, advantage, or disadvantage to redeclaring function parameters as local var开发者_运维百科iables?
Example:
function(param1, param2) {
var param1, param2;
...etc...
}
Seems extremely redundant to me, but maybe I'm missing something...?
Thanks,
Brian
If the names of the declared variables are the same as the ones as the function parameters then it does absolutely nothing. Completely worthless. Doesn't even change the value of the variable.
There is no good reason to ever redeclare a local variable with the same name as a parameter. Most languages wouldn't allow this, but JavaScript allows pretty much everything.
It will be useful, when user didn't pass any thing on function calls.
for example
function X(param1, param2){
param1 = param1 || 1; //set default values if param1 is nothing
param2 = param2 || {};
}
but in your example, you have overwritten function's parameters, so it will be just like
function X(){
var param1, param2;
...
}
Often this is unnecessary, but it can be useful in some cases.
A couple of examples:
If you modify the values of those variables in the function, but need to know what the original value was later in the function, you'll do well to have made a copy up front.
Sometimes it is convenient to have a very descriptive name in the declaration, like first_integer_in_product_list
, but would rather work with just i
when writing code inside the function.
It doesn't hurt anything, and unless you need to do something off the wall like the answer from S. Mark it should be avoided. It can lead to less readable code, and if you're not paying attention to variable scopes or if you lose track of names it can make for a spaghetti warehouse.
You should mention in the post which language you are talking about, in most that would be an error if they had the same name. I assume the most likely reason for being able to do so in some language would be to alter its scope, like make its duration static rather than destroying immediately as the function completes.
精彩评论