简单的JavaScript类封装实现类操作
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了简单的JavaScript类封装实现类操作,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2377字,纯文字阅读大概需要4分钟。
内容图文
想用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
内容总结
以上是互联网集市为您收集整理的简单的JavaScript类封装实现类操作全部内容,希望文章能够帮你解决简单的JavaScript类封装实现类操作所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。