<script> var Shop = function () { this.name = function () { document.write("商店的名字 <br/>"); }, this.local = function () { document.write("商店的位置 <br/>"); } }; var ToolShop = function () { ToolShop.convertASThis.constructor.call(this); this.kind = function () { document.write("卖工具的商店 <br/>"); }, this.time = function () { document.write("工具商店营业时间8:00~16:00 <br/>"); } }; var PetShop = function () { PetShop.convertASThis.constructor.call(this); this.kind = function () { document.write("卖猫狗的商店 <br/>"); }, this.time = function () { document.write("营业时间9:00~15:00 <br/>"); } }; extend(ToolShop, Shop); extend(PetShop, Shop); //========================================================= var Fish_ToolShop = function () { Fish_ToolShop.convertASThis.constructor.call(this); this.material = function () { document.write("钓鱼所用的材料! <br/>"); }; } var Repair_ToolShop = function () { Repair_ToolShop.convertASThis.constructor.call(this); this.material = function () { document.write("修理所用的材料! <br/>"); }; } extend(Repair_ToolShop, ToolShop); extend(Fish_ToolShop, ToolShop); //========================================================= //智能工厂,动态实例化商店 var ShopFactory = { Init: function (shopName) { var tmpObj = eval("new " + shopName + "();"); return tmpObj; } }; //========================================================= //不同的工具商店可能存在多种不同类型的工具,所以存在一个商店的父类但是不能被实例化,需要在子类中重写 var FatherToolShop = function () { this.sellTool = function (kind) { throw new Error(‘this is a abstract class‘); }; }; //这个对象继承FatherToolShop后重写sellTool来来进行实例 var OtherToolShop = function () { }; extend(OtherToolShop, FatherToolShop); //继承之后将原型链中的sellTool方法重写 OtherToolShop.prototype.sellTool = function (kind) { var kind = kind; var kinds = ["Repair_ToolShop", "Fish_ToolShop"]; for (var v in kinds) { if (kinds[v] == kind) { kind = ShopFactory.Init(kind); kind.kind(); //工具商店 kind.time(); //营业时间 break; } } return kind; }; //========================================================= var test = new OtherToolShop(); test.sellTool("Repair_ToolShop").material(); test.sellTool("Fish_ToolShop").material(); </script>
时间: 2024-11-10 07:26:34