Skip to content

Instantly share code, notes, and snippets.

@black-black-cat
Last active June 5, 2016 06:57
Show Gist options
  • Save black-black-cat/d32a13dd52a78803fc4955647fbe0b7f to your computer and use it in GitHub Desktop.
Save black-black-cat/d32a13dd52a78803fc4955647fbe0b7f to your computer and use it in GitHub Desktop.
闭包6-4
// example 1
function a(c) {
// 在a的作用域中声明b
return function b(d) {
// b中使用了a的局部变量c
c += 1;
return c + d;
}
}
// 使b在a的作用域外可访问
var b = a(1);
// 在a的作用域外调用b
// 效果是,a执行完之后,a的局部变量c(闭包变量)不会被销毁(垃圾回收机制销毁)
b(1); // --> 3
b(1); // --> 4
// example 2
/**
* @param {Number} stop 在哪个数字停下来
*/
function si(stop) {
var i = 0;
var interval = setInterval(function () {
// i,interval是闭包变量
console.log(++i);
if (i == stop) {
clearInterval(interval);
console.log('interval cleared');
}
}, 1000);
return interval;
}
// 定时器
var t = si(99);
// 用来手动停止定时器
function stop(t) {
clearInterval(t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment