关于JavaScript变量的Scope

本文详细解析了JavaScript中的作用域概念,包括全局作用域、局部作用域及如何通过立即调用函数表达式(IIFE)来创建私有作用域。同时,文章深入探讨了闭包的概念,解释了为什么在某些情况下使用闭包是必要的,并提供了一个使用闭包解决实际问题的例子。

1 var sth = ""; // Global Scope

2 var foo = function(){

  var sth = ""; // Local Scope

}

3 var foo = function(){

  sth = ""; // Global Scope, this is definitely denied!

}

4 (function(){

  var jQuery = {

    // variable methods or definitions  

  }

  window.jQuery = jQuery;

})(); // Immediately-Invoked Function Expressions, This is used by jQuery and some other liberaries.

point1: the var exsits in var jQuery is very important, without it jQuery will be global scope.

point2: though the jQuery is also global scope, but when another jQuery defined in window, it will also work.

 

according to http://learn.jquery.com/javascript-101/scope/

 

5 closure

for(var i=0;i<5;i++){

  setTimeOut(function(){

    alert(i);  // will not alert correctly~, because the i has already added for 5 times in the fiven 1000 mill-seconds.

  }, 1000);

}

to correct this, we should use closure.

for (var i=0;i<5;i++) {

  setTimeOut(alertFunc(i), i*1000); // why? the function will be called immediately with parameter i, so the alertFunc knows that i, and only i nothing else, then alert 0, 1, 2, 3, 4, end~

}

var alertFunc = function(i){

  alert(i);

}

 

according to http://learn.jquery.com/javascript-101/closures/

转载于:https://www.cnblogs.com/voctrals/p/3706618.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值