在C#中如果我们要访问一个类中的私有变量?如何去做?有两种办法,一种是属性,另外一种就是暴露一个公开的方法,在这个方法里对这个私有变量,看下面的例子。
public sealed class TileInfo { private int _width = 256; private int _height = 256; private IPoint _origin; private ISpatialReference _spatialRef; private Lod[] _lods; public TileInfo() { } public TileInfo(int size,IPoint origin,ISpatialReference srf) { this._width = size; this._height = size; this._origin = ((ICloneable)origin).Clone() as IPoint; this._spatialRef = ((ICloneable)srf).Clone() as ISpatialReference; } public TileInfo(int size,IPoint origin,ISpatialReference srf,Lod[] lods) { this._width = size; this._height = size; this._origin = ((ICloneable)origin).Clone() as IPoint; this._spatialRef = ((ICloneable)srf).Clone() as ISpatialReference; this._lods = lods; } public int Width { get { return _width; } set { _width = value; } } public int Height { get { return _height; } set { _height = value; } } public IPoint Origin { get { return _origin; } set { _origin = value; } } public ISpatialReference SpatialReference { get { return _spatialRef; } set { _spatialRef = value; } } public Lod[] Lods { get { return _lods; } set { _lods = value; } } }
Javascript中没有没有像C#中的类,但是在JS中函数扮演了双重角色,函数可以认为是一个”类“,JS中没有public,private等修饰词,里面的变量就分为globe和函数内部(用var声明,否则是globe的)在JS中的对象可以用JSON描述,如果用JSON的话,可以解决访问对象中的变量
var person = { "name": "liuyu", "id": 1, getName: function () { return this.name} }; alert(person.id) person.say = function (x) { this.id = x; } person.say(2); alert(person.getName());
这种的确可以解决,没有问题,但是这个也有方便的地方,不能当做一个模板(类似类的作用,通过构造函数的参数,实例化多个对象),闭包可以说也是一种为了解决访问私有变量的一种手段。
function Person(Name, id) { //私有变量: var Name = Name; var id = id; //公共变量: this.getName = function () { return Name; }; this.setID = function (x) { id = x; } this.getID = function () { return id; } };
闭包的写法可能不仅仅是这样,有的时候是将内部的这个函数作为返回结果的,如下.
function foo(x) { var tmp = 3; return function (y) { alert(x + y + (++tmp)); } }
闭包其实就是在一个函数内部由定义了一个函数,用这个内部函数对这个外部函数里面的私有变量进行处理,之所以能访问父类函数内部的变量,就说明了这个私有变量没有被释放。很多资料上可能这么说:
- 作为一个函数变量的一个引用 - 当函数返回时,其处于激活状态。
- 一个闭包就是当一个函数返回时,一个没有释放资源的栈区。