javascript 对象封装的常用方式

常规封装

function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}

Person.prototype = {
  constructor: Person,
  sayHello: function () {
    console.log('hello');
  }
}
var b = new Person('张三', 12, '女');
b.sayHello();

将初始化内容放函数中

function Person(info) {
  this._init_(info);
}

Person.prototype = {
  constructor: Person,
  _init_:function(info){
    this.name = info.name;
    this.age = info.age;
    this.sex = info.sex;
  },
  sayHello: function () {
    console.log(this.name);
  }
}
var info = {
  name:'张三',
  age:'12',
  sex:'女'
}
var b = new Person(info);
b.sayHello();//张三
new改造
function Person(info) {
  this._init_(info);
}
Person.prototype =  {
  constructor : Person,
      _init_ : function(info) {
    this.name = info.name;
    this.age = info.age;
    this.sex = info.sex;
  },
  sayHello:function(){
    console.log( this.name );
  }

}
var myNew = function(constructor, args) {
  var o = {};
  o.__proto__ = constructor.prototype; //构造函数的原型属性prototype赋值给o 的原型对象__proto__
  var res = constructor.call(o, args);//以o为上下文调用函数,同时将参数作为数组传递
  var type = typeof res;//如果在构造函数中,return 复合类型,包括对象,函数,和正则表达式,那么就会直接返回这个对象,否则,返回 o
  if (['string', 'number', 'boolean', 'null', 'undefined'].indexOf(type) !== -1) {
    return o;
  }
  return res;
}
var info = {
  name:'张三',
  age:12
}
var b = myNew(Person,info); 
console.log(b);//Person { name: '张三', age: 12, sex: undefined }
b.sayHello();//张三

类jQuery 封装

jQuery 对象具有很强的集成性,可以作为函数调用,也可以做为对象调用,当作为函数调用的时候,她可以无需 new 而返回它的一个实例,很方便。

var Person = (function(window){
  var Person = function(info){
    return new Person.fn.init(info);
  }

  Person.fn=Person.prototype = {
    constructor: Person,
    init:function(){
      this.name = info.name;
      this.sayHello();
    },
    sayHello:function(){
      console.log(this.name);
    }
  }
  Person.fn.init.prototype = Person.prototype;
  return Person;
})()



var info = {
  name:'张三'
}
var a = Person(info);//张三
a.sayHello()//张三

object.create();

var Person = {
  name: 'pawn',
  sayHello: function() {
    console.log(this.name);
  }
}
var p = Object.create(Person);
p.sayHello();//pawn


猜你喜欢

转载自blog.csdn.net/liangrongliu1991/article/details/79654047
今日推荐