JavaScript 工厂模式

梦想的初衷 提交于 2019-12-05 05:26:35
  function FruitMaker() {
    this.cococola = function coco(price) {
      console.log("生成一瓶Coca-Cola,多少钱:" + price);
    }

    this.xuebi = function xuebi(price) {
      console.log("生成一瓶可乐,多少钱:" + price);
    }
  }

  FruitMaker.prototype.make = function (water, price) {
    try {
      var func = this[water];
      func.prototype = FruitMaker.prototype;
      return new func(price);
    } catch (error) {
      console.log("很抱歉, 公司暂时不能生产" + water + "这种果汁, ....");
    }
  }

  var maker = new FruitMaker();
  var cocoCola = maker.make("cococola", "3.1");
  console.log(cocoCola);
  var xuebi = maker.make("xuebi", "3.2");
  console.log(xuebi);

  var fenda = maker.make("fenda", "3.3");
  console.log(fenda);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!