javascript学习之三(闭包)

闭包

概念:
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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值