编程小贴士

给你的编程提供小点子


使用函数化的Javascript代码编写方式

对于Javascript介绍想必大家都耳熟能详啦, 基于函数化的编程语言, 基于浏览器运行的编程语言, web开发语言, 前端开发必备语言, blablabla…

Javascript是一个非常灵活的语言, 可能每一个人对于JS的理解也不尽相同,大家诟病它的基于方法的编程方式, 当然, 很多人也使用面对对象的方式, 基于Prototype的方式,或者简单粗暴的命令式的编程方式, 或者干脆混合起来使用也一样可以运行的很流畅

本文并不讨论所谓的代码可维护性,那种方式更适合编写javascript,我们讨论一下不同书写javascript代码的不同,或许大家自己会有自己的选择和答案啦~~

简单粗暴的命令式编写方式

最初的Javascript用来处理浏览器中DOM的相关操作及其相关事件,比如, 点击操作, 悬浮操作等等等等, 如下的代码可能是大家经常见到的书些方式:

  1. var result;
  2. function getText() {
  3. var someText = prompt(“输入需要处理成首字母大写的英文字母”);
  4. capWords(someText);
  5. alert(result.join(” “));
  6. };
  7. function capWords(input) {
  8. var counter;
  9. var inputArray = input.split(” “);
  10. var transformed = “”;
  11. result = [];
  12. for (counter = 0; counter < inputArray.length; counter++) {
  13. transformed = [
  14. inputArray[counter].charAt(0).toUpperCase(),
  15. inputArray[counter].substring(1)
  16. ].join(“”);
  17. result.push(transformed);
  18. }
  19. };
  20. document.getElementById(“main_button”).onclick = getText;

这种方式代码的书写将遵从从上往下的方式来运行, 这里我们构建了一个getText方法, 通过onlick的调用触发,整个代码的构建比较简单直观,但是有很大的代码隐患,例如,全局变量问题

使用面对对象的编写方式

这种使用prototype的方式来构建OO方式的代码,将帮助解决相关的全局变量问题,并且有效的封装了相关方法

使用关键字:use strict 将保证更好运行性能,老式的onlick方式也被addListener取代,使用IE8之前的浏览器估计也很少了吧~~

  1. (function() {
  2. “use strict”;
  3. var SomeText = function(text) {
  4. this.text = text;
  5. };
  6. SomeText.prototype.capify = function(str) {
  7. var firstLetter = str.charAt(0);
  8. var remainder = str.substring(1);
  9. return [firstLetter.toUpperCase(), remainder].join(“”);
  10. };
  11. SomeText.prototype.capifyWords = function() {
  12. var result = [];
  13. var textArray = this.text.split(” “);
  14. for (var counter = 0; counter < textArray.length; counter++) {
  15. result.push(this.capify(textArray[counter]));
  16. }
  17. return result.join(” “);
  18. };
  19. document.getElementById(“main_button”).addEventListener(“click”, function(e) {
  20. var something = prompt(“输入需要处理成首字母大写的英文字母”);
  21. var newText = new SomeText(something);
  22. alert(newText.capifyWords());
  23. });
  24. }());

虽然OO方法封装代码,并且优化了结构,但是仍旧有一些问题,比如控制自己区域外的一些变量,也不利于测试等等

精简函数化的编写方式

看到如下的代码了吗? 是不是更加纯粹, 仅仅是两个独立的函数

这里这里使用了MAP方法来取代for循环,新的ECMAscript 5标准下,尽量使用Map方法来替代for循环,能帮助解决多余的临时变量问题,并且让代码更加整洁明了

  1. (function() {
  2. “use strict”;
  3. var capify = function(str) {
  4. return [str.charAt(0).toUpperCase(), str.substring(1)].join(“”);
  5. };
  6. var processWords = function(fn, str) {
  7. return str.split(” “).map(fn).join(” “);
  8. };
  9. document.getElementById(“main_button”).addEventListener(“click”, function(e) {
  10. var something = prompt(“输入需要处理成首字母大写的英文字母”);
  11. alert(processWords(capify, something));
  12. });
  13. }());

84 Responses to “ 使用函数化的Javascript代码编写方式 ”

  1. chocopie说道:

    Fi7jH6 new the web visitors, who are wishing for blogging.

  2. Thank you ever so for you post.Much thanks again. Keep writing.

  3. Lung Detox说道:

    You made some nice points there. I looked on the internet for the subject matter and found most individuals will consent with your blog.

  4. kamagra gel说道:

    Im obliged for the blog article.Thanks Again. Fantastic.

  5. Major thanks for the article post.Thanks Again. Much obliged.

  6. W88说道:

    you are in point of fact a just right webmaster.

  7. Im grateful for the blog.Thanks Again. Really Cool.

  8. Well I really liked studying it. This post procured by you is very effective for proper planning.

  9. I truly appreciate this blog post. Great.

  10. I’а†ve recently started a website, the information you provide on this web site has helped me tremendously. Thank you for all of your time & work.

  11. status online说道:

    There is definately a great deal to learn about this subject. I love all of the points you made.

  12. It as nearly impossible to find experienced people on this topic, but you sound like you know what you are talking about! Thanks

  13. share now说道:

    I value the article post.Thanks Again. Want more.

  14. du an Rio Verde说道:

    I will tell your friends to visit this website..Thanks for the article.

  15. anchor说道:

    Im thankful for the post.Really looking forward to read more. Really Cool.

  16. Nwokolo说道:

    you may have an important blog here! would you prefer to make some invite posts on my blog?

  17. Really enjoyed this blog article.Thanks Again. Keep writing.

  18. This is one awesome blog article. Want more.

  19. I wished to compose you one particular extremely little remark to finally say thanks when far more over the

  20. metal recycling说道:

    You should be a part of a contest for one of the best sites online.

  21. hip hop说道:

    My brother suggested I might like this blog. He was totally right. This post truly made my day. You cann at imagine simply how much time I had spent for this info! Thanks!

  22. tu bep dep说道:

    There is apparently a bundle to identify about this. I believe you made certain nice points in features also.

  23. You have brought up a very wonderful points, appreciate it for the post.

  24. yeezy boost 350说道:

    I precisely wished to thank you so much again. I’m not certain what I would have tried without the creative concepts contributed by you over this concern. Certainly was a real difficult setting in my view, however , noticing your expert tactic you resolved the issue made me to leap for joy. Now i’m grateful for the information and as well , expect you comprehend what a powerful job that you’re providing educating the mediocre ones through a site. I’m certain you haven’t encountered all of us.

  25. I will right away seize your rss feed as I can at to find your e-mail subscription link or e-newsletter service. Do you have any? Kindly let me know so that I could subscribe. Thanks.

  26. There is perceptibly a bundle to realize about this. I feel you made various nice points in features also.

  27. khach san说道:

    So pleased to have located this submit.. My personal internet searching seem complete.. thank you. Wonderful feelings you have here.. I value you sharing your point of view..

  28. It is actually a great and useful piece of information. I am glad that you simply shared this helpful info with us. Please keep us up to date like this. Thank you for sharing.

  29. raspberry ketone lean advanced weight loss

  30. online loans说道:

    I regard something truly special in this internet site.

  31. Wow! This could be one particular of the most helpful blogs We ave ever arrive across on this subject. Basically Fantastic. I am also an expert in this topic so I can understand your effort.

  32. sua hat huu co说道:

    really make my blog jump out. Please let me know where you got your theme.

  33. sim viettel说道:

    Major thanks for the article post.Really looking forward to read more. Much obliged.

  34. Really informative blog.Much thanks again. Awesome.

  35. Miracle Ndu说道:

    When I start your Rss feed it seems to be a lot of garbage, is the issue on my side?

  36. click here说道:

    There as certainly a great deal to find out about this issue. I like all of the points you made.

  37. people will pass over your magnificent writing due to this problem.

  38. repair service, routine maintenance and electricity conservation of economic roofing systems will probably be as cost-effective as is possible. And using this

  39. Way cool! Some extremely valid points! I appreciate you penning this post and also the rest of the website is also really good.

  40. Crochet facil说道:

    Thank you ever so for you article.Much thanks again. Want more.

  41. my page说道:

    Really enjoyed this blog post.Thanks Again. Much obliged.

  42. red shoes说道:

    Major thanks for the article post.Really thank you! Will read on

  43. School news说道:

    You made some good points there. I checked on the web to find out more about the issue and found most individuals will go along with your views on this site.

  44. Exams说道:

    I think this is a real great article post.Thanks Again. Really Great.

  45. pretty valuable stuff, overall I believe this is really worth a bookmark, thanks

  46. Thanks-a-mundo for the article.Thanks Again. Cool.

  47. Sites we recommend Excellent blog here! Also your website loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as quickly as yours lol

  48. Your style is really unique compared to other people I ave read stuff from. I appreciate you for posting when you have the opportunity, Guess I will just bookmark this site.

  49. Really excellent information can be found on web blog.

  50. Your current positions continually include much of really up to date info. Where do you come up with this? Just saying you are very resourceful. Thanks again

  51. Some actually good content on this web web site, appreciate it for share. A conservative can be a man who sits and thinks, mostly is located. by Woodrow Wilson.

  52. I?аАТ’аЂа†ll right away grasp your rss feed as I can not to find your e-mail subscription link or newsletter service. Do you ave any? Kindly permit me recognize so that I could subscribe. Thanks.

  53. I was recommended this blog by my cousin. I am not certain whether this put up is written by means of him as nobody else realize such certain approximately my trouble. You are amazing! Thank you!

  54. you ave gotten an ideal weblog right here! would you like to make some invite posts on my weblog?

  55. Odidi说道:

    Wow! This could be one particular of the most beneficial blogs We ave ever arrive across on this subject. Basically Wonderful. I am also a specialist in this topic so I can understand your hard work.

  56. Open Heaven说道:

    Precisely what I was searching for, thanks for posting. There are many victories worse than a defeat. by George Eliot.

  57. Purple your website submit and loved it. Have you at any time considered about visitor publishing on other relevant blogs comparable to your weblog?

  58. Very good blog article.Thanks Again. Really Great.

  59. Looking mail to reading added. Enormous article.Really looking to the fore to interpret more. Keep writing.

  60. I seriously love your blog.. Excellent colors theme. Did you create this website yourself? Please reply back as I

  61. dclm devotionals说道:

    I wanted to thank you for this great read!! I surely enjoying every small bit of it I have you bookmarked to look at new stuff you postaаАа’б‚Т€ТšаЂаŒаАТ’аЂа†

  62. Bula说道:

    This blog is really awesome and also informative. I have found a lot of useful stuff out of this blog. I ad love to come back over and over again. Cheers!

  63. find more here说道:

    There is definately a great deal to know about this topic. I like all of the points you made.

  64. Wonderful items from I like to make use of a treatment for my personal itchy vagina because it helps keep me personally esteem as opposed to hearing simply a doctor.

  65. highland kilts说道:

    When June arrives towards the airport, a man named Roy (Tom Cruise) bumps into her.

  66. click here说道:

    Really informative article.Really looking forward to read more. Want more.

  67. I value the blog.Thanks Again. Really Great.

  68. Rattling clean internet internet site , appreciate it for this post.

  69. Major thankies for the blog article. Keep writing.

  70. post说道:

    So content to possess located this publish.. Seriously beneficial perspective, many thanks for giving.. Great feelings you have here.. Extremely good perception, many thanks for posting..

  71. Share posts说道:

    You can certainly see your enthusiasm within the work you write. The world hopes for more passionate writers like you who aren at afraid to mention how they believe. At all times follow your heart.

  72. Kickboxing说道:

    This is one awesome post.Really looking forward to read more. Want more.

  73. Im thankful for the blog.Thanks Again. Really Cool.

  74. Some truly interesting details you have written.Aided me a lot, just what I was searching for .

  75. Thanks, Your post Comfortably, the article

  76. Thanks for sharing, this is a fantastic article.Really looking forward to read more. Will read on…

  77. to learn more说道:

    Wow! This can be one particular of the most beneficial blogs We ave ever arrive across on this subject. Actually Wonderful. I am also an expert in this topic therefore I can understand your hard work.

  78. Perfectly composed subject material , thankyou for selective information.

  79. Well I sincerely liked studying it. This tip provided by you is very constructive for correct planning.

  80. Several thanks for the fantastic post C IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžd fun reading it! That i really like this weblog.

  81. Im obliged for the blog post.Really looking forward to read more. Cool.

  82. Wow, incredible blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is excellent, let alone the content!

  83. Some genuinely prize blog posts on this site, saved to bookmarks.

  84. situs saya说道:

    sante de et le territoire et sa batarde sera je

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>