简体   繁体   中英

JavaScript closures and scoping: How to pass an outer scope variable to a callback function which is passed as an argument?

My code is like this:

im.size((function(a, b) {
  console.log(b);
  console.log(im);
})(im));

The Object im has a function size, which expects a callback function. It passes the parameters a and b to the callback function. However I need to have the object im to be available within the callback. Therefore I pass it from the outside as an argument, however this "overwrites" the arguments a and b passed to the callback.

The output is:

 undefined [My Object]

If I do:

im.size(function(a, b) {
  console.log(b);
  console.log(im);
});

The output is:

 17 [My object] // edited: was undefined before

How can I pass the im object to be available in the scope of the callback as well as getting the variables passed to the callback? A bit of explanation would also be nice.

Edit: Actually the outer scope is accessible in my callback example. Is this also true for asynchronous callbacks and WHY is the outer scope accessible this way?

The second example should work too, giving that im is defined in that scope (deduced from the first example).

If a variable is accessible at the scope a function is defined in, it will be accessible within that function too. You could have done im.size(im); to pass im to size (for example), so if you do im.size(function() {}) , im will be accessible to that function as well.

Is this also true for asynchronous callbacks?

Yes.

WHY is the outer scope accessible this way?

That's just how it works - it's lexically in scope, so it is accessible. Other languages require you to explicitly state which variables you want to close over, JS doesn't.

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