调用 function变量
Simply put, a scope limiter is a self-executing function that defines a variables, performs a task, and clears those variables so that their scope is limited to the function itself. Take the following JavaScript code, for example:
简而言之,作用域限制器是一种自执行函数,可定义变量,执行任务并清除这些变量,以使它们的作用域仅限于函数本身。 以以下JavaScript代码为例:
/* do task 1: */
var lynx = $$('a');
var divs = $$('div');
//(do stuff with links and divs)
/* do task 2 */
var lynx = $$('a'); //error: lynx already defined!
var lis = $$('li');
//(do stuff with links and list items)
Everything above works but the second task can "see" the variables used to complete task one. This is undesirable as those variables from the first task could cause problems with later tasks. The better way to complete the two tasks is to use scope limiters for each:
上面的所有内容都可以工作,但是第二个任务可以“看到”用于完成任务一的变量。 这是不希望的,因为第一个任务中的那些变量可能会导致后续任务出现问题。 完成这两项任务的更好方法是为每一项使用范围限制器:
/* do task 1: */
(function() {
var lynx = $$('a');
var divs = $$('div');
//(do stuff with links and divs)
})();
/* do task 2 */
(function() {
var lynx = $$('a');
var lis = $$('li');
//(do stuff with links and list items)
})();
Sweet! Now the variables from the first task have scope only within their executed function scope and cannot affect other JavaScript within the "parent" scope.
甜! 现在,第一个任务的变量仅在其执行的函数范围内具有作用域,而不会影响“父”范围内的其他JavaScript。
Clean code FTW! Keep these techniques in mind when you're writing code that will be repurposed!
清除代码FTW! 在编写将被重新利用的代码时,请记住这些技巧!
调用 function变量