前言
我是歌谣 最好的种树是十年前 其次是现在 今天继续给大家带来的是闭包的讲解
环境配置
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"
}
}
基本案例
function test(callback){
var a=1
callback(a)
}
test(function(a){
console.log(a)
})
运行结果
回调案例
function test(title,callback,callback2){
var _title=`Title:${title}`
var _zhtitle=`标题:${title}`
callback(_title)
callback2(_zhtitle)
}
test("我是 歌谣",function(title){
console.log(title)
},function(title){
console.log(title)
})
运行结果
计算
function calculate(a, b, type,callback) {
let res = 0;
let sign = '+';
switch (type) {
case 'PLUS':
res = a + b;
sign = '+'
break
case 'MINUS':
res = a - b;
sign = '-'
break
case 'MUL':
res = a * b;
sign = '*'
break
case 'DIV':
res = a / b;
sign = '/'
break
default:
res = a + b;
sign = '+'
break
}
callback&&callback(a,b,sign,res)
return {
a, b, sign, res
}
}
// const {a,b,sign,res}=calculate(1,2,'DIV')
// console.log(`${a}${b}${sign}${res}`)
calculate(1,2,'DIV',(a,b,sign,res)=>{
console.log(`${a}${b}${sign}${res}`)
})
运行结果
验证
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>回调</title>
</head>
<body>
<input type="test" id="username">
<input type="password" id="password">
<button id="loginBtn">登录</button>
<script type="module" src="./index3.js"></script>
</body>
</html>
index3.js
import { checkUserInfo, checkCommet } from "./validate"
const OUsername = document.querySelector("#username")
const OPassword = document.querySelector("#password")
const OLoginbtn = document.querySelector("#loginBtn")
function validate(field) {
debugger
return function (data) {
switch (field) {
case 'USER_INFO':
return checkUserInfo(data)
case 'USER_COMMET':
return checkCommet(data)
default:
throw new Error("验证失败")
}
}
}
function loginAction(userInfo, validate) {
const { errCode, errMsg, value } = validate(userInfo)
console.log(errCode, errMsg, value)
if(errCode==1){
throw new Error(errMsg)
}
console.log(value)
}
OLoginbtn.addEventListener('click', () => {
const username = OUsername.value
const password = OPassword.value
console.log(username,password,"data is")
loginAction({ username, password }, validate('USER_INFO'))
}, false)
validate.js
export function checkUserInfo({username,password}){
if(username.trim().length<6){
return {
errCode:1,
errMsg:"username不能小于6",
value:username
}
}
if(password.trim().length<6){
return {
errCode:1,
errMsg:"password不能小于6",
value:password
}
}
return {
errCode:0,
errMsg:"ok",
value:{
username,password
}
}
}
export function checkCommet(data){
}
运行结果
阻塞 后端代码
const express=require("express")
const app=express()
app.all('*',(req,res,next)=>{
res.header('Access-Control-Allow-Origin',"*")
res.header('Access-Control-Allow-Methods',"POST,GET")
next();
})
app.get('/getdata',(req,res)=>{
res.json({
name:"geyao",
age:18
})
})
app.listen(3003,()=>{
console.log("ok")
})
启动
前端
const data=$.ajax("http://localhost:3003/getdata",{
async:false,
// success(data){
// console.log(data)
// }
}).responseJSON
console.log(data)
console.log(123)
运行结果
异步问题同步化
后端
const express=require("express")
const app=express()
app.all('*',(req,res,next)=>{
res.header('Access-Control-Allow-Origin',"*")
res.header('Access-Control-Allow-Methods',"POST,GET")
next();
})
app.get('/getdata',(req,res)=>{
res.json({
name:"geyao",
age:18
})
})
app.listen(3003,()=>{
console.log("ok")
})
前端
function getData(){
return new Promise((resolve,reject)=>{
$.ajax("http://localhost:3003/getdata",{
success(data){
resolve(data)
}
})
})
}
// getData().then(data=>{
// console.log(data)
// console.log(123)
// })
async function test(){
const data=await getData();
console.log(data)
console.log(123)
}
test()
console.log(234)
运行结果
watcher实现
index.js
const Delfln = (() => {
const watcher=[
]
function useReactive(state) {
return new Proxy(state,{
get(target,key){
return Reflect.get[target,key]
},
set(target,key,value){
update(watcher[key].collection,value)
watcher[key].cb(target[key],value)
return Reflect.set(target,key,value)
}
})
}
function useWatcher(collection,key,callback) {
!watcher[key]&&(watcher[key]={})
!watcher[key].collection&&(watcher[key].collection=[])
watcher[key].cb=callback
watcher[key].collection=[...watcher[key].collection,...collection]
console.log(watcher,"watcher is")
}
function update(collection,value){
collection.forEach(el=>{
el.innerText=value
})
}
return {
useReactive,
useWatcher
}
})()
const { useReactive, useWatcher } = Delfln
const state = useReactive({
title: "This is Title",
content: "This is Content"
})
useWatcher([
document.querySelector("h1"),
document.querySelector("h2")
], 'title', (prev, cur) => {
console.log("watch title"+prev, cur)
})
useWatcher([
document.querySelector("p"),
document.querySelector("span")
], 'content', (prev, cur) => {
console.log("watch content"+prev, cur)
})
function render(){
document.querySelector('h1').innerText=state.title,
document.querySelector('h2').innerText=state.title
document.querySelector('p').innerText=state.content
document.querySelector('span').innerText=state.content
}
setTimeout(()=>{
state.title="这是标题",
state.content="这是内容"
},1000)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>回调</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<!-- <input type="test" id="username">
<input type="password" id="password">
<button id="loginBtn">登录</button> -->
<h1>
</h1>
<h2></h2>
<p></p>
<span></span>
<script type="module" src="./index6.js"></script>
</body>
</html>