JavaScript 闭包和面向对象设计

日期: 2017-07-21         浏览量: 2870

过程与数据的结合是形容面向对象中的 “对象” 时经常使用的表达。对象以方法是形式包含了过程,而闭包则是过程中以环境的形式包含了数据。

通常用面向对象思想能实现的功能,用闭包也能实现。

下面来看看和闭包相关的代码:


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);

}

var extent = new extent();


extent.call();        //输出 1

extent.call();        //输出 2

extent.call();        //输出 3