闭包
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="onTest('显示')">显示</button>
<button onclick="onTest('+1')">+1</button>
<button onclick="onTest('+2')">+2</button>
<button onclick="onTest('归零')">归零</button>
<script>
function outerFunction() {
let outerVariable = 1;
function innerFunction(data) {
if (data.type === '显示') {
console.log(outerVariable);
} else if (data.type === '+1') {
outerVariable = outerVariable + 1
} else if (data.type === '+2') {
outerVariable = outerVariable + 2
} else if (data.type === '归零') {
outerVariable = 0;
}
}
return innerFunction;
}
const closure = outerFunction();
function onTest(str) {
closure({ type: str })
}
</script>
</body>
</html>
本文标题:闭包
本文链接:https://www.haomeiwen.com/subject/usbvwdtx.html
网友评论