简体   繁体   中英

Explicitly scope a variable inside a function

I'm reading this article and there is a paragraph:

If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:

 (function() {
        var myProperty = "hello world";
        alert(myProperty);
  })();
 alert(typeof(myProperty)); // undefined

I met with this already but still need some clarification why should I need to explicitly scope a variable inside a function when variables are implicitly scoped inside a function in Javascript.

Could you explain the purpose of this?

thank you

for (var i = 0; i < 10; i++) {
  setTimeout(function() { console.log(i) }, 10);
}

// alerts 10, 10 times

for (var i = 0; i < 10; i++) {
  (function(i) {
    // explicitly scope i
    setTimout(function() { console.log(i) }, 10);
  })(i);
}

When generating functions inside other functions and accessing variables up the scope chain through closure scope it may be useful to "explicitly scope" a variable inside the outer function.

Although this is an anti pattern. The correct solution would be

var generateLogger = function(i) {
  return function() { console.log(i); };
}

for (var i = 0; i < 10; i++) {
  setTimeout(generateLogger(i), 10);
}

Since generating functions in a loop is inefficient and bad practice.

There are no real use cases of "explicitly scoping" variables that can't be avoided by not creating functions inside other functions.

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