封装性

js中处处是对象,这样就少不了封装,js有两种封装,包括如下:

1,使用约定优先的原则,将所有私有变量以_开头

var Person = function (no, name, age)  
 11        {  
 12            this.setNo(no);  
 13            this.setName(name);  
 14            this.setAge(age);  
 15        }  
 16        Person.prototype = {  
 17            constructor: Person,  
 18            checkNo: function (no)  
 19            {  
 20                if (!no.constructor == "string" || no.length != 4)  
 21                    throw new Error("学号必须为4位");  
 22            },  
 23            setNo: function (no)  
 24            {  
 25                this.checkNo(no);  
 26                this._no = no;  
 27            }, getNo: function ()  
 28            {  
 29                return this._no;  
 30            }, setName: function (name)  
 31            {  
 32                this._name = name;  
 33            }, getName: function ()  
 34            {  
 35                return this._name;  
 36            }, setAge: function (age)  
 37            {  
 38                this._age = age;  
 39            }, getAge: function ()  
 40            {  
 41                return this._age;  
 42            }, toString: function ()  
 43            {  
 44                return "no = " + this._no + " , name = " + this._name + " , age = " + this._age;  
 45            }  
 46        };  
 
当然这种封装仅仅以_开头,还是可以直接访问的,最起码成员变量的getter,setter方法都是prototype,总体来说还是不错的。当然还有第二种方法

2.严格封装
使用这种方式虽然可以严格实现封装,但是带来的问题是get和set方法都不能存储在prototype中,都是存储在对象中的,无形中又增加了内存
this.  
                    getAge = function ()  
         {  
                 return _age;  
           }  
  
            this.setNo(no);  
            this.setName(name);  
             this.setAge(age);  
     }  
去掉了this.属性名,严格的实现了封装,但是只能通过get、 set访问成员变量,占用了一部分内存。
posted @ 2021-12-04 23:26  Purgatory  阅读(97)  评论(0)    收藏  举报