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

猜你喜欢

转载自www.cnblogs.com/yafuture/p/10535294.html