JS封装

1、对象原型封装

基本思想是在原函数中建立getter和setter方法,之后在原函数的原型进行其他操作。

    好处:只能通过get和set访问函数中的数据,实现额真正的封装,实现了属性的私有化

    劣处:这样做所有的方法都在对象中,会增加内存的开销

测试demo:

/** 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");

console.log(per.toString());

per.setNo("0001");

console.log(per.toString());

per.setAge(25);

console.log(per.toString());

 

2、闭包封装

基本思想:构建闭包函数,在函数内部返回匿名函数,在匿名函数内部构建方法,在每次进行实例化调用的时候,其实都是每次都是调用返回函数的子函数,同时能保持对对象中的属性的共享

    好处:可以做到实例对象向对象属性的共享并且保持私有

    坏处:所有的get和set都存储在对象中,不能存储在prototype中,会增加开销

测试demo

 /** 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());

原文地址:https://www.cnblogs.com/ranyonsue/p/11227459.html