匿名函数与闭包

Js里的变量作用域:全局变量和局部变量。而在函数内部,可以直接访问全局变量,在定义变量时,没有使用var关键字的就是全部变量。在函数外部是无法读取函数内部的变量。为了解决这一问题 ,出现了闭包。所以闭包就是:可以访问其他函数的局部变量(内部变量)的函数,由于js作用域链结构,子对象可以一级一级向上搜索其所有父对象的变量,所以,闭包就是存在于函数内部的函数。注意:内部函数可以访问定义在他们外部函数的参数和变量(除了thisarguments)之外。

闭包的特性:闭包里作用域返回的局部变量资源不会立即被销毁回收,闭包可以将变量驻留在内存中,由于闭包里的变量一直存在于内存中,可能会造成性能问题。在IE中滥用闭包会造成内存泄漏。闭包依赖于其父函数,只有重新调用其父函数,闭包的值才会被清除,否则。闭包的值一直存在于内存中。



匿名函数执行的两种方式(1)把匿名函数赋值给变量;

var add=function (a,b){
console.log(a+b);
}
add(1,2);

(2)匿名函数自执行:

(function (a,b){
alert(a+b);
})(1,2);

(3) 把匿名函数自执行的返回值赋值给变量;

var add=(function (a,b){
return a+b;
)(1,2);
console.log(add);



关于this对象:this在全局作用下指的是window对象,在对象内部指的是这个对象。而闭包中的this却指的是window对象,因为闭包并不属于这个对象的属性和方法。

<!doctype html>
<html>
<head>
</head>
<body>
	<script>
		var user="the window";
		var box={
			user:"the box",
			getUser:function (){
				return this.user;
			}
		}
		console.log(user); //the window
		console.log(box.getUser());//the box
		
		var user="the window";
		var box={
			user:"the box",
			getUser:function (){
				return function (){
					return this.user;
				}
			}
		}
		console.log(user); //the window
		console.log(box.getUser()());//the window,闭包在运行时this指的是window全局对象,闭包中变量的值一直驻留在内存中,模拟全局变量

		//为了让闭包中的this指向box对象,以下两种办法
		var user="the window";
		var box={
			user:"the box",
			getUser:function (){
				return function (){
					return this.user;
				}
			}
		}
		//对象冒充
		console.log(box.getUser().call(box));//the box



		var user="the window";
		var box={
			user:"the box",
			getUser:function (){
				//这里的this指的是box对象
				//用that保存this的值
				var that=this;
				return function (){
					return that.user;
				}
			}
		}
		console.log(box.getUser()());//the box
	</script>
</body>
</html>

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值