02 常见设计模式

不知道怎么封装代码?看看这几种设计模式吧!

工厂模式

面向对象

function popup(type, content, color) {
  // 如果是通过 new 调用的,返回对应类型的弹窗
  if (this instanceof popup) {
    return new this[type](content, color);
  } else {
    // 如果不是 new 调用的,使用 new 调用,会走到上面那行代码
    return new popup(type, content, color);
  }
}

// 各种类型的弹窗全部挂载在原型上成为实例方法
popup.prototype.infoPopup = function (content, color) {};
popup.prototype.confirmPopup = function (content, color) {};
popup.prototype.cancelPopup = function (content, color) {};

封装成模块

单例模式

测试一下

最后更新于

这有帮助吗?