前端歌谣-第贰拾陆课-闭包
前言
我是歌谣 最好的种树是十年前 其次是现在 今天继续给大家带来的是闭包的讲解
环境配置
npm init -y
yarn add vite -D
修改page.json配置端口
{
"name": "demo1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "vite --port 3002"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"vite": "^4.4.9"
}
}
案例1
function test1(){
function test2(){
var b=2;
console.log(a)
}
var a=1;
return test2()
}
var c=3
var test3=test1();
分析
案例2
function test(){
var n=100
function add(){
n++
console.log(n)
}
function reduce(){
n--
console.log(n)
}
return [add,reduce]
}
var arr=test()
arr[0]()
arr[1]()
运行结果
案例2
function breadMsg(num) {
var breadNum = arguments[0] || 10
function supply() {
breadNum += 10
console.log(breadNum)
}
function sale() {
breadNum -= 10
console.log(breadNum)
}
return [supply, sale]
}
var breadMsg = breadMsg(50)
breadMsg[0](10)
运行结果
案列3
function sunSched(){
var sunSched=''
var opration={
setSched:function(thing){
sunSched=thing
},
showSched:function(){
console.log("MY schedule on sunday is "+sunSched)
}
}
return opration
}
var sunSch=sunSched()
sunSch.setSched("studying")
sunSch.showSched()