函数闭包-js-v1.0.0
2019-07-30 本文已影响0人
一点金光
---
title:函数闭包
date: 2018-06-09 16:29:00
updated: 2018-06-10 12:00:00
categories:
- 语言基础
- 函数编程
tags:
- nodejs
---
#什么是它?
一个函数。在它的内部访问外部的变量,在它的外部访问它的变量。
#解决问题?
解决--引用的变量可能发生变化的问题
//发现问题:
function before() {
let result = [];
for(let i = 0;i<10; i++){
result[i] = function () {
console.info(i)
}
}
return result
}
//解决问题:
function after() {
let result = [];
for(let i = 0;i<10; i++){
result[i]= function (num) {//{1}
return function() {//{2}
// {2}访问函数外部的变量num
console.info(num);
}
}(i)
}
return result
}
解决--内存泄漏问题
//发现问题:
function before() {
var el = document.getElementById("app")
el.onclick = function(){
aler(el.id) // 这样会导致闭包引用外层的el,当执行完showId后,el无法释放
}
}
//解决问题:
function after() {
var el = document.getElementById("app")
//{1}
var id = el.id
el.onclick = function(){
aler(id) //{2}
}
el = null // {3}主动释放el
}
解决--改上下文问题
//发现问题:
var object = {
name:"object",
getName:function() {
let that = this //{1}
return function() {
console.info(that.name)//{2}
}
}
}
object.getName()() // underfined
//解决问题:
var object = {
name:"object",
getName:function() {
let that = this //{1}
return function() {
console.info(that.name)//{2}
}
}
}
object.getName()() // object
解决--递归调用问题
//发现问题:
function beforeFactorial(num) {
if(num<= 1) {
return 1;
} else {
return num * beforeFactorial(num-1)
}
}
let anotherFactorial = beforeFactorial
beforeFactorial = null
anotherFactorial(4) // 报错 ,因为最好是return num* arguments.callee(num-1),arguments.callee指向当前执行函数,但是在严格模式下不能使用该属性也会报错,所以借助闭包来实现
//解决问题:
let newFactorial = (function f(num){
if(num<1) {return 1}
else {
return num* f(num-1)
}
})
解决--变量提升问题
//发现问题:
//es6没出来之前,用var定义变量存在变量提升问题
for(var i=0; i<10; i++){
console.info(i)
}
alert(i) // 变量提升,弹出10
//解决问题:
(function () {
for(var i=0; i<10; i++){
console.info(i)
}
})()
alert(i) // underfined