admin管理员组

文章数量:1317910

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 variables?

Example:

function(param1, param2) {
  var param1, param2;
  ...etc...
}

Seems extremely redundant to me, but maybe I'm missing something...?

Thanks,

Brian

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 variables?

Example:

function(param1, param2) {
  var param1, param2;
  ...etc...
}

Seems extremely redundant to me, but maybe I'm missing something...?

Thanks,

Brian

Share Improve this question edited Jan 22, 2010 at 4:45 YOU 124k34 gold badges190 silver badges222 bronze badges asked Jan 22, 2010 at 4:42 user256430user256430 3,6435 gold badges35 silver badges34 bronze badges 1
  • is it Javascript? By the way, nice nickname. – littlegreen Commented Jan 22, 2010 at 4:58
Add a ment  | 

6 Answers 6

Reset to default 5

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 pletes.

本文标签: javascriptRedeclaring function parameters as variablesStack Overflow