发如飞絮——js设计模式(1)

110 阅读1分钟

创建类

1. 原型模式

function proto(userName, userAge) {
  proto.prototype.userInfo = {
    name: userName,
    age: userAge,
  };
  proto.prototype.show = function() {
    console.log('lilei.show',this.userInfo);
  }
}
let lilei = new proto('liLei', 38);
console.log('lilei.userInfo',lilei.userInfo);
  • 输出结果

lilei.userInfo { name: 'liLei', age: 38 }

  • 注意:原型模式只能够重复创建对象,传入新参数会覆盖原值

2.单例模式

let human;
function single(name, age) {
  if (!human) {
    human = {};
  }
  human.name = name;
  human.age = age;
  return human;
}

console.log(single('lilei', 45));
console.log(single('hanmei', 20));
  • 输出结果

单例模式.PNG

好处:可多次创建生成数据集合,对象数组等