`
jingwei.yang
  • 浏览: 3165 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

闭包也就这玩意

阅读更多

闭包也叫closure这东西听起来挺玄乎,《js犀牛书》上搞了一计数器作为例子,如下:

 

function counter() {
    var n = 0;
    return {
        count: function() { return n++; },
        reset: function() { n = 0; }
    };
}
var c = counter(), d = counter();   // Create two counters
c.count()                           // => 0
d.count()                           // => 0: they count independently
c.reset()                           // reset() and count() methods share state
c.count()                           // => 0: because we reset c
d.count()                           // => 1: d was not reset

 我看了半天,没觉得有啥大不了的,感觉很自然,我转念一想,这不就是把函数当成面向对象中的类了嘛

 

public class counter() {
    private int n = 0;
  
    public int count{ return n++; },
    public void reset{ n = 0; }
}
counter c = new counter();
counter d = new counter();   // Create two counters
c.count()                           // => 0
d.count()                           // => 0: they count independently
c.reset()                           // reset() and count() methods share state
c.count()                           // => 0: because we reset c
d.count()                           // => 1: d was not reset

 肿么样?是这回事吧,其实闭包就是:

“把父函数当作对象(object)使用,把闭包当作它的公用方法(Public Method),把内部变量当作它的私有属性(private value)。”

欢迎拍砖。

 

一个较为详细的关于闭包的文章如下:

深入理解js闭包

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics