js封装
首页 > >    作者:lininn   2019年3月22日 16:12 星期五   热度:1736°   百度已收录  
时间:2019-3-22 16:12   热度:1736° 

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

jq方式:


var  Person=(function(window){
       var Person=function(data){
            return new Person.fn.init(data);
       }
       Person.fn=Person.prototype={
           constructor:Person,
           data1:{
               val:12
           },
           init:function(data){
               this.data=data;
               this.sayHello=function(){
                   console.log(this.data+"say Hello");
               }
           },
           sayHi:function(){
               console.log(this.data);
               console.log(this.data1);
           },
        
       };
       Person.fn.init.prototype=Person.fn;
       return Person;
})();
var p1=Person("lining");
p1.sayHello();
p1.sayHi();




二维码加载中...
本文作者:lininn      文章标题: js封装
本文地址:?post=323
版权声明:若无注明,本文皆为“覆手为雨”原创,转载请保留文章出处。
分享本文至:

返回顶部    首页    手机版本    后花园   会员注册   
版权所有:覆手为雨    站长: lininn