javascript设计模式(二)-安全工厂方式

  function Factory(type, content) {
    if (this instanceof Factory) {
      // 直接调用函数
      return new this[type](content);
    } else {
      return new Factory(type, content);
    }
  };

  // 定义一个静态方法
  Factory.insertHTML = function(content) {
    let div = document.createElement('div');
    div.innerHTML = content;
    div.style.border = '1px solid #f00';
    document.getElementById('container').appendChild(div);
  };
  Factory.prototype = {
    JAVA: function (content) {
      Factory.insertHTML(content);
    },
    PHP: function (content) {
      Factory.insertHTML(content);
    },
    JAVASCRIPT: function (content) {
      Factory.insertHTML(content);
    },
    PYTHON: function (content) {
      Factory.insertHTML(content);
    }
  };
  const dataList = [
    {
      type: "JAVA",
      content: "java培训"
    },
    {
      type: "PHP",
      content: "PHP培训"
    },
    {
      type: "JAVASCRIPT",
      content: "JAVASCRIPT培训"
    },
    {
      type: "PYTHON",
      content: "PYTHON培训"
    }
  ];
  for (let item of dataList) {
    Factory(item.type, item.content);
  }
上一篇:JAVA学习笔记——Set集合及其子类


下一篇:cpu高分析方法