標籤:
<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>
JS “eval智能” 原廠模式