js 闭包
通过闭包封装私有变量
function a() { //函数外访问不到 var s = 3; //使外部能够获得s变量的值 this.f = function () { return s } //改变s的值 this.add=function(){ s++ } } var t = new a() t.add() console.log(t.f())
通过回调函数,每个方法拥有独立的私有变量
<div id="box1">box1</div>
<div id="box2">box2</div>
<script>
function ani(elementId) {
var elem = document.getElementById(elementId)
console.log(elem.style)
var count = 0
var timer = setInterval(function () {
if (count < 100) {
elem.style.margin = count + "px"
count++
console.log(elem.style.left)
} else {
clearInterval(timer)
}
}, 10)
}
ani("box1")
ani("box2")
</script>

浙公网安备 33010602011771号