闭包和面向对象

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

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

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
原文地址:https://www.cnblogs.com/stone-it/p/7326040.html