关于javascript的closure&&使用闭包实现私有成员的方法

(一)

1.闭包的本质

A closure is a special kind of object that combines two things: a function, and the environment in which that function was created.
2.闭包的作用
A closure lets you associate some data (the environment) with a function that operates on that data. 
Using closures in this way provides a number of benefits that are normally associated with object oriented programming, in particular data hiding and encapsulation.
3.闭包和面向对象语言的相似之处
 This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.
Consequently, you can use a closure anywhere that you might normally use an object with only a single method.
(二)
javascript 实现私有成员变量和函数
var counter = (function(){
  var privateCounter = 0;
  function changeBy(val) {
   privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };   
})();
1.首先这是一个自调用匿名函数。
2.这里的私有成员包括成员变量和成员函数。
3.返回的三个对象可以视为该对象的公有函数或者公有成员变量。
posted @ 2015-10-20 14:17  Santiago_1991  阅读(179)  评论(0编辑  收藏  举报