17

Given the following JavaScript:

var someFunction = function(id) {
  //do some stuff
  var modifyId = function(id) {
     //do some stuff
     outer.id = id; //is there any way to modify the id variable in the outer scope from here?
  }
}

How do you modify the id passed into the outer function scope from within the inner function scope?

1
  • All the replies into one: you can't, you have to rename one of them Commented Oct 22, 2010 at 23:20

4 Answers 4

17

Unfortunately you can't. By naming the parameter in the nested function id, you've shadowed the parameter in the outer function. Javascript contains no facility for accessing the shadowed name. The only option is to choose a different name for one of the variables.

Sign up to request clarification or add additional context in comments.

Comments

2

No, there isn't. From within a function, there's no way (something weird in Mozilla's code or ES5 aside) to refer to the scope as a context in any explicit way, and there's no way to climb up the lexical scope chain in any direct way.

Good question though.

Comments

1
var someFunction = function(id) {
  //do some stuff
  var oid = id;
  var modifyId = function(id) {
     //do some stuff
     // you can access the outer id via the oid variable
  }
}

But, yes, you should just rename one of the formal parameters.

2 Comments

At first I thought this worked, but it won't work if id is a primitive. Setting oid = "BLAH" from the inner function will not change the value of id. If it were an object, both id and oid would point to the same object, which is almost the effect you want (you still couldn't change what object id points to by calling oid = {a:1}
@Juan Yes. Since id is a string (I assume), that means that my work-around is pretty much useless in this case. So the only solution remains to avoid formal parameters with the same names in nested functions.
1

Why can't you just rename one of the variables?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.