Peter Kellner
Peter Kellner

Reputation: 15498

JavaScript scoping, parameter in function same as local variable in function?

when I have a function, does the parameter passed in have the same scope to a callback method inside the function? that is, in the following function are both xx and yy valid?

onMyFunction: function(component) {
  var myLocal = 7;
  my.load({
    callbackfunction: function() {
       // can I access both
       var xx = component;
       var yy = myLocal;
    }
  });

Upvotes: 0

Views: 53

Answers (3)

Felix Kling
Felix Kling

Reputation: 816482

Parameters are scoped exactly like local variables and for all intents and purposes behave exactly like local variables.

In fact, when a function is executed, parameters and variables are stored in the same internal "map", so during runtime, it would not even be possible to distinguish between parameters and variables. At least according to the specification.

Upvotes: 1

diogoriba
diogoriba

Reputation: 352

Yes, javascript does scoping mainly by functions so all the references you have available in a function block will also be available to any function or block declared within it.

If you're interested in the subject, i'd recommend https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/README.md especially the part on Function/Block Scope and also Scope Closures.

:)

Upvotes: 0

CaldasGSM
CaldasGSM

Reputation: 3062

yes they are both valid.. that is what closures are for...

Upvotes: 4

Related Questions