簡單的JavaScript類封裝實現類操作

想用JS實現類封裝結構,根據紅色警戒寫了一個超小示例。

非常希望有高手提改進意見!以後擴充。

RA2.js

 1 /***RA2***/
 2 
 3 console.log("RA2");
 4 var CountryGroup = Object.freeze({"A":"A","R":"R"});
 5 //console.log(CountryGroup.R);
 6 //console.log(Object.keys(CountryGroup)[CountryGroup.A]);
 7 
 8 var TankType = Object.freeze({"CannonTank":"CannonTank","LightTank":"LightTank"});
 9 
10 var Country = function(name, countryGroup){
11     
12     var _name = name, 
13         _countryGroup = countryGroup
14 
15     this.GetName = function(){return _name;}
16     this.SetName = function(newName){_name = newName;}
17     this.GetCountryGroup = function(){return _countryGroup;}
18     this.SetCountryGroup = function(newCountryGroup){_countryGroup = newCountryGroup;}
19 
20     this.CreateHeavyFactory = function(){
21         var heavyFactory = new HeavyFactory(this);
22         return heavyFactory;
23     }
24 
25 }
26 
27 var HeavyFactory = function(country){
28     var _country = country
29 
30     this.GetCountry = function(){return _country;}
31     this.SetCountry = function(newCountry){_country = newCountry;}
32 
33     this.CreateTank = function(country, tankType){
34         var tank;
35         switch(tankType){
36             case TankType.CannonTank:
37                 tank = new CannonTank(country);
38                 break;
39             default:
40                 tank = new LightTank(country);
41                 break;
42         }
43         
44         return tank;
45     }
46 
47 }
48 
49 var Tank = function(country){
50     var _country = country
51 
52     this.Run = function(){}
53 
54     this.Fire = function(){}
55 }
56 
57 var LightTank = function(country){
58     Tank.call(this,country);
59 
60     this.Run = function(){console.log("fast run");}
61 
62     this.Fire = function(){console.log("common fire");}
63 }
64 
65 var CannonTank = function(country){
66     Tank.call(this,country);
67 
68     this.Run = function(){console.log("slow run");}
69 
70     this.Fire = function(){console.log("fast fire");}
71 }

 

調用方法示例:

 1 <script type="text/javascript">
 2 
 3 var c = new Country("CHN",CountryGroup.R);
 4 var hf = c.CreateHeavyFactory(c);
 5 
 6 var tankA = hf.CreateTank(c, TankType.CannonTank);
 7 tankA.Run();
 8 tankA.Fire();
 9 
10 var tankB = hf.CreateTank(c, TankType.LightTank);
11 tankB.Run();
12 tankB.Fire();
13 
14 </script>
How to use it

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章