作用域和闭包

223 阅读1分钟

作用域和闭包

1.闭包

作用域应用的特殊情况,有两种表现:

a.函数作为参数被传递

b.函数作为返回值被返回

闭包:自由变量的查找,实在函数定义的地方,向上级作用域查找不是在执行的地方!!!!!

2.this取值是函数执行的时候确定的

this的不同应用场景,如何取值

a.当做普通函数被调用

b.使用 call apply bind

c.作为对象方法被调用

d.在class的方法中调用

e.箭头函数

//手写bind函数
function fn1(a,b){
	console.log('this',this)
	console.log(a,b)
	return 'this is fn1'
}
const fn2 = fn1.bind({x:100},10,20,30)
const res = fn2
console.log(res)
//模拟bind
Function.prototype.bind1 = function (){
	//将参数拆解维数组
	const args = Array.prototype.slice..call(arguments)
	
	//获取this(数组第一项)
	const t = args.shift()
	
	//fn1.bind 中的fn1
	const self = this();
	
	//返回一个函数
	return function(){
		return self.apply(t,args)
	}
}

3.实际开发中的闭包的应用

1.隐藏数据

eg:做一个简单的cache工具

//cache 闭包隐藏数据 只提供api
fuction createCache(){
	const data = {} //闭包中的数据,被隐藏,不被外界访问
	return {
		set:function(key,val){
			data[key] = val
		},
		get:function(key,val){
			return data[key]
		}
	}
}

const c = createCache()
c.set('a',100)
console.log(c.get('a'))