• JavaScrpt常用的封装方法


    1.闭包封装。在这个封装方法中,所有的实例成员都共享属性和方法, 使得所有得方法和属性都私有且对象间共享

    (function ($) {
      var Person = function(name) {
                return new Person.fn.init(name);
            }
    
            Person.fn = Person.prototype = {
                constructor: Person,
                init: function(name) {
                    this.name = name;
                    this.sayHello = function() {
                        this.makeArray();
                    }
                },
                makeArray: function() {
                    console.log(this.name);
                }
            }
    
            Person.fn.init.prototype = Person.fn;
    
            return Person;
    })(jQuery);

    2.对象原型封装

    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());
  • 相关阅读:
    什么是代理
    简易的屏幕适配
    SourceTree 操作简介
    project/target/product的简易区别
    iOS申请真机调试证书-图文详解
    关于UINavigationController的backBarButtonItem定制问题
    pat1008
    pat1005
    pat1019-简单模拟题
    ie6-ie8中不支持opacity透明度的解决方法
  • 原文地址:https://www.cnblogs.com/yafuture/p/10535294.html
Copyright © 2020-2023  润新知