调用 function变量_使用(function(){})()限制变量范围

调用 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! 在编写将被重新利用的代码时,请记住这些技巧!

翻译自: https://davidwalsh.name/javascript-closures

调用 function变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值