In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)06/01 Report--
模仿块级作用域
Javascript中没有块级作用域的概念,这意味着在块语句中定义的变量,实际上是在包含函数中而非语句中创建的
1 function outputNumbers(count){2 for (var i = 0; i < count; i++){3 console.log(i);4 }5 console.log(i);6 }
在for循环中定义的局部变量i可以再for循环外访问,因为变量i是定义在outputNumbers()的活动对象中的,因此从它有定义开始,就可以在函数内部随处访问它。
1 function outputNumbers(count){2 for (var i = 0; i < count; i++){3 console.log(i);4 }5 var i;6 console.log(i);7 }
遇到这种情况,他只会对后续的声明视而不见。匿名函数可以用来模仿块级作用域并避免这个问题。
1 (function(){2 //这里是块级作用域3 })();
以上代码定义并立即调用了一个匿名函数。将函数声明包含在一堆圆括号中,表示它实际上是一个函数表达式。而紧随其后的另一对圆括号会立即调用这个函数。
注意:
1 function(){2 //这里是块级作用域3 }(); //出错
function关键字表示一个函数声明的开始,而函数声明后面不能跟圆括号。然而,函数表达式的后面可以跟圆括号。要将函数声明转换成函数表达式。
无论在什么地方,只要临时需要一些变量,就可以使用私有作用域
1 function outputNumbers(count){2 (function(){3 for (var i = 0; i < count; i++){4 console.log(i);5 }6 })();7 console.log(i); //i is not defined8 }
这种技术经常用在全局作用域中被用在函数外部,从而限制向全局作用域中添加过多的变量和函数
1 (function(){2 var now = new Date();3 if (now.getMonth() == 0 && now.getDate() == 1){4 alert("Happy new year");5 }6 })();
其中now现在是匿名函数中的局部变量,而我们不必在全局作用域中创建它。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.