最近我们知了堂技术大军到处跑,真的是应了那句马不停蹄,反正就是一个学校接着一个学校的跑,中间都没有停过,过程中我也是一路技术开挂的弄,从JAVA到物联网arm再到前端Vue和JS高级部分,差点搞得我换不过脑袋和思维,其中在分享JS技术之余,我尝试着用JAVA的封装特性来对JS做了深入的应用,也是其乐无穷,今天就把一些心得和大家作点分享吧。
1、对象原型封装
基本思想是在原函数中建立getter和setter方法,之后在原函数的原型进行其他操作。
好处:只能通过get和set访问函数中的数据,实现额真正的封装,实现了属性的私有化
劣处:这样做所有的方法都在对象中,会增加内存的开销

/** 1、这种封装个方法getter和setter方法都在该构造函数中,数据较多的时候占用的内存较大* */
function Person(name,age,no){ 
   this._name=name; 
   this._age=age; this._no=no; 
   this.checkNo=function(no){
       if(!no.constructor == "string"|| no.length!=4) 
         throw new Error("学号必须为4位"); };
    //var _no,_age,_name; 
   this.setNo=function(no){ 
      this.checkNo(no); this._no=no;
    }; this.getNo=function(){ 
      return this._no; }; 
   this.setName=function(name){ this._name=name; }; this.getName=function(){ return this._name; }; this.setAge=function(age){ this._age=age; }; this.getAge=function(){ return this._age; }; this.setNo(no); this.setName(name); this.setAge(age);}Person.prototype={ toString:function(){ return"no = " + this.getNo() + " , name = " + this.getName() + " , age = " + this.getAge(); }};var per=new Person("lili",23,"0004");sconsole.log(per.toString());per.setNo("0001");console.log(per.toString());per.setAge(25);console.log(per.toString());

2、闭包封装
基本思想:构建闭包函数,在函数内部返回匿名函数,在匿名函数内部构建方法,在每次进行实例化调用的时候,其实都是每次都是调用返回函数的子函数,同时能保持对对象中的属性的共享
好处:可以做到实例对象向对象属性的共享并且保持私有
坏处:所有的get和set都存储在对象中,不能存储在prototype中,会增加开销

/*
    * 2、闭包的封装方式,在这个封装方法中,所有的实例成员都共享属性和方法
    * 使得所有得方法和属性都私有且对象间共享
    * */
    var Person=(function(){
        /*共享函数*/
        let checkNo=function(no){
            if(!no.constructor=="string"||no.length!=4){
                throw new Error("必须为4位数");
            };
        };
        let times=0;//共享数据
        return function(no,name,age){
            console.log(times++);
            this.setNo=function(no){
                checkNo(no);
                this._no=no;
            };
            this.getNo=function(){
                return this._no;
            };
            this.setName=function(name){
                this._name=name;
            };
            this.getName=function(){
                return this._name;
            };
            this.setAge=function(age){
                this._age=age;
            };
            this.getAge=function(age){
                return this._age;
            };
            this.setNo(no);
            this.setAge(age);
            this.setName(name);
 
        }
    })();
    Person.prototype={
        constructor:Person,
        toString:function(){
            return "no = " + this._no + " , name = " + this._name + " , age = " + this._age;
        }
    }
 
    let per=new Person("0001",15,"simu");//输出之后times会逐渐增加,变为1、2、3
    let per1=new Person("0002",15,"simu1");
    let per2=new Person("0003",15,"simu2");
    console.log( per.toString());
    console.log( per1.toString());
    console.log( per2.toString());


最后修改:2019 年 06 月 28 日
如果觉得我的文章对你有用,请随意赞赏