简体   繁体   中英

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;
    }
  });

是的,它们都是有效的..那就是闭包是为了...

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 .

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.

:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM