闭包
概念:
1. function的参数也被包含在闭包之中
2. 所有的外部变量都属于闭包可访问的范围(外部域),包括那些在闭包后面创建出来的变量
3. 在同一个域中,不可以访问后面才创建的变量
闭包占用了内存,释放闭包的方式:
1. 通过javascripte引擎的GC垃圾回收机制
2. 刷新或者关闭当前页面
使用闭包
私有变量
function Ninja() {
var slices = 0;
this.getSlices = function() {
return slices;
}
this.slice = function() {
slices++;
}
}
var ninja = new Ninja();
ninja.slice();
assert(ninja.getSlices() == 1, "We're able to access the internal slice data."); assert(ninja.slices == undefined, "And the private data is inaccessible to us.");
回调
jquery中ajax的使用:
<div id="testSubject"></div>
<button type="button" id="testButton">Go!</button>
<script type="text/javascript">
jQuery('#testButton').click(function(){
var elem$ = jQuery("#testSubject");
elem$.html("Loading...");
jQuery.ajax({
url: "test.html",
success: function(html){
assert(elem$,"We can see elem$, via the closure for this callback.");
elem$.html(html);
}
});
});
</script>