FactoryパターンのJavaScript

  //工厂
  function FruitMaker() {
     //function 后不带方法名,这里cococola未定义,make return时,返回 FruitMaker.cococola
    this.cococola = function cococola (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);

あなたが新製品を開発する必要がある場合(ここでは - >ファンタ)

  //生产线(新开发产品)
  FruitMaker.prototype.extend = function (obj) {
    for (var key in obj) {
      this[key] = obj[key];
    }
  };

通話時間:

  maker.extend({
    "fenda": function coco(price) {
      console.log("生成一瓶fenda,多少钱:" + price);
    }
  });

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

おすすめ

転載: www.cnblogs.com/tangge/p/11909265.html