举例如下, 不做过多说明了, 应该能看懂(特权方法就是能访问私有变量又是类公开的方法)
这么做好处是可以做到属性私有, 坏处没法继承. 一般情况下, 不用继承的类这么写比较好, 比如 N 多插件源码 (不一定 jq 哦) 大体都是这个逻辑.
- //Person 类
- var Person = (function(){
- // 私有静态变量
- var sexArr = ["male","female"];
- var personNum = 0;
- // 私有静态函数
- function getSex(sex){
- return (sexArr.indexOf(sex)==-1)? sexArr[0] : sex;
- }
- // 构造函数
- function fn(name,sex){
- // 私有变量
- var n,s;
- // 公有特权方法
- this.getName = function(){
- return n;
- }
- // 公有特权方法
- this.setName = function(name){
- if(!name||typeof name !== 'string'){
- throw new Error("constructor needs name to be a string!")
- }
- n = name;
- }
- // 公有特权方法
- this.getSex = function(){
- return s ? s : sexArr[0];
- }
- // 公有特权方法
- this.setSex = function(sex){
- s = getSex(sex);
- }
- personNum ++;
- this.setName(name);
- this.setSex(sex);
- }
- //prototype
- fn.prototype = {
- // 实例公有方法
- getInfo : function(){
- return 'name:' + this.getName() +', sex:' + this.getSex();
- }
- };
- // 公有静态属性
- fn.ClassInfo = 'Person class needs name as a argument!';
- // 公有静态方法
- fn.getTotalNum = function(){
- return personNum;
- };
- // 返回构造函数
- return fn;
- })();
- // 使用如下
- // 我
- var me = new Person('laoyao');
- alert(me.getName());//laoyao
- alert(me.getSex());//male
- alert(me.getInfo());//name: laoyao , sex: male
- alert(Person.getTotalNum());//1
- //GF
- var myGF = new Person('unknow');
- alert(myGF.getName());//unknow
- alert(myGF.getSex());//male
- myGF.setSex('female');
- alert(myGF.getSex());//female
- alert(myGF.getInfo());//name: unknow, sex: female
- alert(Person.getTotalNum());//2[/code]
来源: http://www.qdfuns.com/article/17398/d0938b51a361b3a90be9bd1ba7c153d9.html