如何产生闭包?
作用域应用的特殊情况有两种表现
- 函数作为参数本传递
- 函数作为返回值被返回
// 函数作为返回值
function create() {
const a = 100
return function () {
console.log(a)
}
}
const fn = create()
const a = 200
fn() // 100
// 函数作为参数被传递
function print(fn) {
const a = 200
fn()
}
const a = 100
function fn() {
console.log(a)
}
print(fn) // 100
函数的自由变量取决于函数定义的地方跟执行的地方没关系
this
this一般用于普通函数,对象方法,call ,apply ,bind,class,箭头函数中使用较多
- 普通函数中的this
function fn(){
console.log(this);
}
fn(); //相当于下面的window.fn();
window.fn();
- 对象方法中出现this
let pox={
name:'小红',
run:function(){
console.log(this.name)//this
}
}
pox.run();// pox 小红
pox调用的run所以run方法中的this指向
let obj={name:'小明'}
let pox={
name:'小红',
run:function(){
console.log(this.name)
}
}
// 对象方法中的this.指向方法的调用者。
pox.run();// pox 小红
pox.run.call(obj)// 小明
pox.run.apply(obj);// 小明
pox.run.bind(obj)();//小明
相同点call/apply/bind()都可以改变this指向第一个参数
不同点:bind()需要手动执行
function foo(){
// argument=[参数] 类数组/伪数组
let arg=arguments;
let arr=[4,5,6]
// arg.push(4) 借用数组
// Array.prototype.push.call(arg,4) // arg==[1,2,3,4]
Array.prototype.push.apply(arg,arr) // arg==[1,2,3,4,5,6]
// Array.prototype.push.bind(arg)(4) // arg==[1,2,3,4]
console.log(arg);//[1,2,3]
}
foo(1,2,3)
不同点:call第二个参数为单个数值,apply()第二个参数为数组
- class中的this指向new 后的实列对象
class Person{
constructor(name,age){
this.name=name;
this.age=age
}
say(){
console.log(`我叫${this.name}年龄是${this.age}`)
}
}
let lsy=new Person('李士乐',21);
lsy.say();// 我叫李士乐年龄是21
console.log(lsy);// {name:'李士乐',age:21}
class中的this指向new 后的实列对象
- 特殊情况
对象方法中的this,指向当前对象(因为当前对象执行了方法)。
setTimeout函数中的this,相当于普通函数中的this,因为setTimeout触发的函数执行,并不是外部对象执行的。
setTimeout中函数是箭头函数,this为当前对象。因为箭头函数中的this始终是父级上下文中的this.
- 需要注意的是
- this去什么值是在执行时确定的,定义时无法确定
手写bind:
// 模拟 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)
}
}
function fn1(a, b, c) {
console.log('this', this)
console.log(a, b, c)
return 'this is fn1'
}
const fn2 = fn1.bind1({x: 100}, 10, 20, 30)
const res = fn2()
console.log(res)
this总结(重要)
普通函数中调用,this指向window
对象方法中调用,this指向当前对象
call apply bind中调用, this指向被传入的对象
class中的方法中调用, this指向实例对象
箭头函数,this就是父级上下文中的this
闭包应用场景,封装对象的私有属性和方法
隐藏数据
做一个简单的缓存工具
// 闭包隐藏数据,只提供 API
function createCache() {
const num=100
const data = {} // 闭包中的数据,被隐藏,不被外界访问
return {
num:num,
set: function (key, val) {
data[key] = val
},
get: function (key) {
return data[key]
}
}
}
const c = createCache()
console.log(c.num)//num此时就作为c私有属性
c.set('a', 100) //set此时作为c的私有方法
console.log( c.get('a') )
闭包应用场景闭包作用回调函数
<body>
<a href="#" id="as1">20</a>
<a href="#" id="as2">40</a>
</body>
<script>
function changeSize(size){
return function(){
document.body.style.fontSize=size+'px';
}
}
var size20=changeSize(20);
var size40=changeSize(40);
document.getElementById('as1').onclick=size20;
document.getElementById('as2').onclick=size40;
</script>
闭包应用场景3,函数节流防抖
<body>
<!-- 函数防抖是指在函数被高频触发时当停止触发后延时n秒再执行函数,
(即每次触发都清理延时函数再次开始计时),一般用于resize scroll,mousemove -->
<!-- 函数节流 原理 函数被高频出发时延时n秒后才会再次执行,防抖主要是用户触发一次时间后,延迟一段时间触发,
而节流会规定的事件内触发一次事件 -->
</body>
<script>
// 函数节流:是确保函数特定的时间内至多执行一次。
// 函数防抖:是函数在特定的时间内不被再调用后执行。
//防抖
var debounce = function(func, delay) {
var timer = null
return function() {
var that = this;
var args = arguments;
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
func.apply(that, args);
}, delay)
}
}
ipt.addEventListener('keyup', debounce(function(e){
console.log(e.target.value);
}, 400))
</script>
补充
// 闭包会造成页面性能问题 在ie中可能导致内存泄漏
function a(){
var num =10;
return function(){
return ++num;
}
}
// var inc =a();
// console.log(inc());
// console.log(inc());
// inc=null;
//也可这样写 a()获取当前函数 再调用
//因为生成的函数inc也是个闭包 这个闭包再次访问到变量num
console.log(a()());
console.log(a()());
//每个复函数调用完成,都会形成新的闭包,父函数中的变量会始终在内存中,
// 相当于缓存,小心消耗问题