zoukankan      html  css  js  c++  java
  • 闭包和面向对象

    对象以方法的形式包含了过程,而闭包则是在过程中以环境的形式包含了数据。通常用面向对象思想能实现的功能,用闭包也能实现。

    如下这段闭包相关的代码:

    var extent = function(){
        var value = 0;
        return {
            call: function(){
                value++;
                console.log( value );
            }
        }
    };
    
    var extent = extent();
    
    extent.call();   //  输出: 1
    extent.call();   //  输出: 2
    extent.call();   //  输出: 3
    

    换成面向对象的写法如下:

    var extent = {
        value: 0,
        call: function(){
            this.value++;
            console.log(this.value);
        }
    }
    
    extent.call();   //  输出: 1
    extent.call();   //  输出: 2
    extent.call();   //  输出: 3
    

    或者

    var Extent = function(){
        this.value = 0;
    }
    Extent.prototype.call = function(){
        this.value++;
        console.log(this.value)
    }
    
    extent.call();   //  输出: 1
    extent.call();   //  输出: 2
    extent.call();   //  输出: 3
    
  • 相关阅读:
    debian修改crontab默认编辑器为vim
    正确用DD测试磁盘读写速度
    西数WD2T硬盘分区对齐的方法
    优化UITableView
    登录功能验证处理
    登录注册界面
    navigationbar
    tab bar controller
    ios之coretext
    ios之coredata
  • 原文地址:https://www.cnblogs.com/stone-it/p/7326040.html
Copyright © 2011-2022 走看看