编程小贴士

给你的编程提供小点子


如何让你的JavaScript代码更加语义化

语义化这个词在 HTML 中用的比较多,即根据内容的结构化选择合适的标签。其作用不容小觑:

  • 赋予标签含义,让代码结构更加清晰,虽然我们可以在标签上添加 class 来标识,但这种通过属性来表示本体的形式会显得不够直接,而且在一定程度上也有冗余。
  • 优化搜索引擎(SEO),结构良好的网页对搜索引擎的亲和力是很高的,百度和 google 也给出了很多网页结构化的建议(规范),方便他们抓取网页。
  • 利于设备解析,如盲人阅读器对页面的分析,目前淘宝很多网页都是支持盲人阅读的,这种体验上的优化得利于网页的良好结构和语义化表达。
  • 便于开发者维护,在参加工作之前,很多程序员都是单人开发模式,单人开发无所谓代码结构,自己看得懂就差不多了,一旦走向工作岗位,会发现,以前的鄙习有点让自己捉襟见肘了。

W3C Group 工作组在 web 规范上持续贡献,他们的目标也是期望整个互联网的发展态势稳定统一起来。不扯远了,回到本文需要阐述的重点:如何语义化 JavaScript 代码?

一、先看看那些不易读懂的 JavaScript 代码

1. 判断

 

// 数据类型判断
if(Object.prototype.toString.call(str) === “[object String]”){     // doSomething();
};  // 文件类型判断
if(/.*.css(?=?|$)/.test(“/path/to/main.css”)){
    // doSomething();
}

 

2. 清空一个队列

 

var Queue = ["test1", "test2", "test3"]; // 常见方式
Queue.length = 0; Queue = [];

 

3. 注册一个变量

 

// 注册
var repos = {};  repos[“a”] = {    name: “a”,    content: {} };  repos[“b”] = {    name: “b”,    content: {} };

 

上面几个例子倒不至于看不懂,程序都特别简单,第一个例子中,我们通过 Object 原型链上的 toString 方法来判断一个变量是否为 string 类型,以及使用正则来判断一个文件是不是 css 文件。代码写起来比较轻松,倘若我们同时需要判断多个对象是否为多个类型中的一种呢?再比如我们需要在一串代码中提取 require 依赖关系呢,是否应该思考下如何组织自己的代码?

在第二个例子中,将数组的长度设置为 0,或者使用空数组来重置这个变量,都是十分常见的方式,但目前的场景是清空一个队列,我们是否可以使用更加语义化的形式来呈现?比如我们只需要清空该队列的前五个和后三个 item 呢?

第三个例子中,变量的注册,把一堆注册放在一起,上面的形式确实也是一目了然,如果 a b c d 等都是分隔穿插在几百行代码之间呢?突然来个 repos[“x”] 这样是否显得有些不太直观。

为了说明本文所倡导的思想,上面的几个解释都有些含糊和牵强,请往下看。

二、提高代码语义性

针对上述三个案例,用更加语义化的方式来呈现代码:

1. 语义化变量

 

// 类型判断
function isType(type){     return function(o){         return Object.prototype.toString.call(o) === '[object ' + type + ']';     } }  var isString = isType(“String”); var isObject = isType("Object"); var isArray = isType("Array");   isString("I'm Barret Lee."); isArray([1,2,3]); isObject({});

 

我觉得不需要太多的解释,对比

 

if(Object.prototype.toString.call(str) === “[object String]”){     // code here...
}

 

显得清新多了吧。

 

// 提取常量
var isCss = /.*.css(?=?|$)/; isCss.test(“/path/to/main.css”);

 

不管 isCss 这个正则代码有多长,当我们看到 isCss 这个单词就可以顾名思义。很多人写正则都不会将正则单独提取出来使用某个有意义的变量去存储,加注释还好,要是不加注释,后续开发者就只能硬着头皮看懂正则去理解代码的含义。

这样的处理,实际上是增加了代码量,不过从工程角度去审视,有助于提高开发效率以及代码的组织性。

2. 语义化行为

 

var Queue = ["test1", "test2", "test3"]; Queue.splice(0, Queue.length);

 

上面代码具有很强的语义性,从索引为 0 的地方开始,直到队列最后,删除 Queue 中所有的 item。这种写法的扩展性也更好:

 

Queue.splice(2, 4); // 删除从索引为 2,往后的 4 个元素

 

这只是个小例子,有些行为是需要很多代码组合处理的,如果没有很好的组合同一行为的代码,整个结构就显得十分涣散,不利于阅读。

 

// 注册
var repos = [];  function register(o){    repos[o.name] = o; }  register({   name: “a”,   content: {} });

 

对比我们之前

 

repos[“a”] = {    name: “a”,    content: {} };

 

语义化程度是不是有所提高~

三、小结

代码的优化,需要考虑的维度很多。但是代码的优化并不是减少代码量,有的时候我们需要增加代码来提高代码的可阅读性。

  • 正确标记变量
  • 封装某个动作
  • 注意函数的写法
  • 不容易理解的东西,加注释

109 Responses to “ 如何让你的JavaScript代码更加语义化 ”

  1. me suba说道:

    mDMP6Y Well I truly liked studying it. This post provided by you is very helpful for accurate planning.

  2. watch movies说道:

    I truly appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You ave made my day! Thank you again

  3. writing is my passion that as why it is quick for me to do post writing in significantly less than a hour or so a

  4. animal coloring说道:

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

  5. mca说道:

    Say, you got a nice article.Thanks Again. Really Great.

  6. This is a topic which is near to my heart Take care! Where are your contact details though?

  7. 389poker说道:

    Thank you for another fantastic post. Where else could anybody get that type of information in

  8. find this说道:

    You have made some good points there. I looked on the net to find out more about the issue and found most people will go along with your views on this website.

  9. Woah! I am really enjoying the template/theme of this blog. It as simple, yet effective.

  10. Thanks again for the article post.Really thank you! Great.

  11. webpage说道:

    This genuinely answered my challenge, thank you!

  12. W88说道:

    Really enjoyed this blog post.Much thanks again. Will read on

  13. Major thanks for the post.Thanks Again. Will read on

  14. The world hopes for more passionate writers like you who aren at afraid to say how they believe. At all times follow your heart.

  15. cheap taxi说道:

    We think you should read this I am still learning from you, as I am trying to reach my goals. I definitely love reading all that is posted on your blog.Keep the tips coming. I enjoyed it!

  16. we prefer to honor numerous other online sites on the internet, even though they aren

  17. wow, awesome blog.Much thanks again. Really Great.

  18. You completed various fine points there. I did a search on the matter and found most folks will have the same opinion with your blog.

  19. Your style is so unique in comparison to other folks I have read stuff from. Thanks for posting when you ave got the opportunity, Guess I all just book mark this page.

  20. NIW说道:

    Thank you for your blog article.Thanks Again. Fantastic.

  21. Nwokolo说道:

    Looking around I like to look around the web, regularly I will just go to Digg and follow thru

  22. The thing that All people Ought To Know Involving E commerce, Modify that E commerce in to a full-blown Goldmine

  23. pretty helpful stuff, overall I consider this is well worth a bookmark, thanks

  24. Wow, great article.Really looking forward to read more. Really Cool.

  25. I was able to find good advice from your blog articles.

  26. in particular near my personal peers. Gratitudes a ton; coming from we all.

  27. budget dumpster说道:

    Looking forward to reading more. Great article post.

  28. Thanks-a-mundo for the article. Want more.

  29. Really appreciate you sharing this article.Much thanks again. Will read on

  30. Informative article, totally what I wanted to find.

  31. browse说道:

    Utterly pent content material , regards for entropy.

  32. Thanks a lot for the blog.Really thank you! Fantastic.

  33. I think other web-site proprietors should take this website as an model, very clean and great user genial style and design, let alone the content. You are an expert in this topic!

  34. This unique blog is obviously educating additionally informative. I have picked up a lot of handy advices out of this blog. I ad love to come back over and over again. Thanks!

  35. kien vang说道:

    Than?s for the post. ? all cаА аЂа•аА аБТ–tainly аАааАТƒomeback.

  36. I truly appreciate this blog.Really thank you! Want more.

  37. I see something truly special in this website.

  38. play说道:

    Wow, awesome blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is excellent, as well as the content!

  39. Elena Matei说道:

    Perfectly pent written content, appreciate it for entropy. The earth was made round so we would not see too far down the road. by Karen Blixen.

  40. money说道:

    This submit truly made my day. You can not consider simply how a lot time

  41. healthy说道:

    Wow! Thank you! I always wanted to write on my website something like that. Can I include a portion of your post to my site?

  42. I regard something genuinely special in this website.

  43. Keep up the great work , I read few blog posts on this internet site and I conceive that your weblog is rattling interesting and contains lots of good info.

  44. Thank you ever so for you article.Much thanks again. Really Cool.

  45. Louis Vuitton For Sale ??????30????????????????5??????????????? | ????????

  46. I really liked your blog article.Really thank you! Will read on…

  47. value说道:

    Muchos Gracias for your blog post.Really looking forward to read more. Really Great.

  48. Looking forward to reading more. Great blog post.Really thank you! Want more.

  49. School news说道:

    user in his/her brain that how a user can be aware of it.

  50. School admission说道:

    Utterly indited subject matter, regards for information.

  51. ps4 ark servers说道:

    If you ask me, in excess of a couple working together to empty desired goals, often have unlimited electric power.

  52. Major thanks for the blog article.Really looking forward to read more. Really Great.

  53. Rattling great info can be found on site.

  54. This is one awesome blog article.Really looking forward to read more. Keep writing.

  55. Thanks for sharing this very good piece. Very interesting ideas! (as always, btw)

  56. You in fact dealt with several engaging items in this post. I came across it by employing Bing and IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžve got to admit that I am now subscribed to your site, it really is very decent (:

  57. Open heavens说道:

    Very nice blog post. I certainly appreciate this site. Continue the good work!

  58. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is wonderful, as well as the content!

  59. Thank you ever so for you post.Thanks Again. Awesome.

  60. cris urzua说道:

    I really liked your post.Thanks Again. Really Great.

  61. Im obliged for the blog post. Really Great.

  62. Im thankful for the article post.Thanks Again. Great.

  63. Thanks for great post. I read it with big pleasure. I look forward to the next article.

  64. hotel说道:

    There is certainly a lot to find out about this subject. I love all of the points you ave made.

  65. Very good blog.Much thanks again. Really Cool.

  66. Thank you for sharing this great piece. Very interesting ideas! (as always, btw)

  67. Sinhce the admin of this site iss working, no hesitation very

  68. Im grateful for the blog.Much thanks again. Really Great.

  69. I truly appreciate this blog.Really looking forward to read more. Keep writing.

  70. It as not that I want to copy your web site, but I really like the design and style. Could you tell me which style are you using? Or was it especially designed?

  71. It as great that you are getting ideas from this paragraph as well as from our discussion made here.|

  72. go to source说道:

    Looking forward to reading more. Great article.Really thank you! Cool.

  73. explore说道:

    IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžm a extended time watcher and I just believed IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžd drop by and say hi there there for your extremely initially time.

  74. The most beneficial and clear News and why it means a whole lot.

  75. When I saw this page was like wow. Thanks for putting your effort in publishing this article.

  76. Thanks for sharing, this is a fantastic blog post. Much obliged.

  77. dizayn Samara说道:

    I think this is a real great blog article.Really thank you! Great.

  78. see this website说道:

    Whats Happening i am new to this, I stumbled upon this I ave discovered It positively useful and it has aided me out loads. I hope to contribute & help different users like its aided me. Good job.

  79. click here说道:

    It as great that you are getting ideas from this piece of writing as well as from our argument made at this time.

  80. Way cool! Some extremely valid points! I appreciate you writing this article and also the rest of the site is very good.

  81. We should definitely care for our natural world, but also a little bit more of our children, especially obesity in children.

  82. start my own blog in the near future. Anyhow, should you have any recommendations or techniques for new blog owners please share.

  83. Singapore Real Estate Links How can I place a bookmark to this site so that I can be aware of new posting? Your article is extremely good!

  84. we like to honor several other web web sites on the web, even when they aren

  85. It’а†s actually a nice and useful piece of info. I am happy that you shared this useful information with us. Please keep us up to date like this. Thank you for sharing.

  86. Share posts说道:

    I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You ave made my day! Thank you again.

  87. visit说道:

    I will not talk about your competence, the write-up just disgusting

  88. this post reminds me of my old room mate! He always kept

  89. wow, awesome blog article.Really looking forward to read more. Fantastic.

  90. It cаА аЂаn bаА аЂа• seeen and ju?ged only by watching the

  91. You need to take part in a contest for the most effective blogs on the web. I will suggest this website!

  92. Your style is unique in comparison to other folks I have read stuff from. Thank you for posting when you ave got the opportunity, Guess I all just book mark this site.

  93. click for more说道:

    I think you have mentioned some very interesting points, thankyou for the post.

  94. know. The design and style look great though! Hope you get the

  95. click here说道:

    very nice submit, i certainly love this website, carry on it

  96. caratulas CD说道:

    The league as new contract with the womens peyton manning jersey; they can

  97. Rising prices will drive housing sales for years to come

  98. previous to and you are just too fantastic. I really like what

  99. This very blog is without a doubt educating as well as amusing. I have picked helluva helpful tips out of this source. I ad love to come back every once in a while. Thanks a lot!

  100. Zelda说道:

    There is certainly a lot to know about this subject. I like all the points you ave made.

  101. Your style is so unique in comparison to other people I ave read stuff from. Many thanks for posting when you have the opportunity, Guess I all just bookmark this web site.

  102. Usually I don at read article on blogs, however I wish to say that this write-up very compelled me to take a look at and do it! Your writing taste has been amazed me. Thank you, quite nice post.

  103. dong ho seiko说道:

    Im thankful for the post.Thanks Again. Really Great.

  104. tham trang tri说道:

    some truly fantastic content on this internet site , thankyou for contribution.

  105. bon tam bang go说道:

    Very neat article.Thanks Again. Great. porno gifs

  106. check here说道:

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

  107. It is best to take part in a contest for among the best blogs on the web. I all suggest this website!

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>