

我们知道JS中私有属性的实现本质就是 var + closure。如下
 代码如下:
function Person(n, a){ 
 // public 
 this.name = n; 
 // private 
 var age = a; 
 this.getName = function(){ 
 return this.name; 
 } 
 this.getAge = function(){ 
 return age; 
 } 
} 
测试如下,age是私有的,使用点操作符无法获取到,而只能使用getName方法。
 代码如下:
var p = new Person('jack',23); 
console.log(p.age); // undefined 
console.log(p.getAge()); // 23 
以上没什么稀奇的,下面我们使用一个工具函数来实现。 
 代码如下:
/** 
 * @param {String} className 
 * @param {Function} classImp 
 */
function $class(className, classImp){ 
 function clazz(){ 
 if(typeof this.init == "function"){ 
 this.init.apply(this, arguments); 
 } 
 } 
 classImp.call(clazz.prototype); 
 window[className] = clazz; 
} 
写一个类 
 代码如下:
$class('Person', function(){ 
 // 私有属性都定义在这 
 var age = ''; 
 this.init = function(n, a){ 
 // 共有属性挂在this上,初始化 
 this.name = n; 
 // 私有属性初始化 
 age = a; 
 }; 
 this.getName = function(){ 
 return this.name; 
 }; 
 this.getAge = function(){ 
 return age; 
 } 
}); 
new一个实例对象 
 代码如下:
var p = new Person('jack',23); 
console.log(p.name); // jack 共有的可使用点操作符获取 
console.log(p.age); // undefined 私有的不能通过点操作符获取 
console.log(p.getAge()); // 23 私有的age只能通过共有的方法getAge获取 
 
