前端开发规范:命名规范、html规范、css规范、js规范

开发 前端
一个好的程序员肯定是要能书写可维护的代码,而不是一次性的代码,怎么能让团队当中其他人甚至一段时间时候你再看你某个时候写的代码也能看懂呢,这就需要规范你的代码了。

 前端开发规范:命名规范、html规范、css规范、js规范

一个好的程序员肯定是要能书写可维护的代码,而不是一次性的代码,怎么能让团队当中其他人甚至一段时间时候你再看你某个时候写的代码也能看懂呢,这就需要规范你的代码了。我是有一点强迫症的人,上周我们后端给我了一个CanUsename的接口(该接口的目的是判断输入的目的地是否是4级目的地),我真的是崩溃的。我只是觉得这个名字不够语义化,但是让我自己想一个名字我又想不出来,于是我就在想,如果有一套命名规范的话,那么以后起名字就不用发愁了,直接按照规范来就好了

命名

驼峰式命名法介绍

  • Pascal Case 大驼峰式命名法:首字母大写。eg:StudentInfo、UserInfo、ProductInfo
  • Camel Case 小驼峰式命名法:首字母小写。eg:studentInfo、userInfo、productInfo文件资源命名
  • 文件名不得含有空格
  • 文件名建议只使用小写字母,不使用大写字母。( 为了醒目,某些说明文件的文件名,可以使用大写字母,比如README、LICENSE。 )
  • 文件名包含多个单词时,单词之间建议使用半角的连词线 ( - ) 分隔。
  • 引入资源使用相对路径,不要指定资源所带的具体协议 ( http:,https: ) ,除非这两者协议都不可用。

不推荐:

  1. <script src="http://cdn.com/foundation.min.js"></script> 

推荐

  1. <script src="//cdn.com/foundation.min.js"></script> 

变量命名

命名方式 : 小驼峰式命名方法命名规范 : 类型+对象描述的方式,如果没有明确的类型,就可以使前缀为名词

前端开发规范:命名规范、html规范、css规范、js规范

推荐

  1. var tableTitle = "LoginTable" 

不推荐

  1. var getTitle = "LoginTable"

函数

命名方式 : 小驼峰方式 ( 构造函数使用大驼峰命名法 )命名规则 : 前缀为动词

前端开发规范:命名规范、html规范、css规范、js规范

 

 

推荐:

  1. //是否可阅读 
  2. function canRead(){ 
  3.     return true
  4.  
  5. //获取姓名 
  6. function getName{ 
  7.     return this.name 
  8. }

常量

命名方法 : 全部大写命名规范 : 使用大写字母和下划线来组合命名,下划线用以分割单词。推荐:

  1. var MAX_COUNT = 10; 
  2.  var URL = 'http://www.baidu.com';

类的成员

  • 公共属性和方法 : 同变量命名方式
  • 私有属性和方法 : 前缀为下划线(_)后面跟公共属性和方法一样的命名方式

推荐(将name换成this是不是更熟悉了呢)

  1. function Student(name) { 
  2.     var _name = name; // 私有成员 
  3.  
  4.     // 公共方法 
  5.     this.getName = function () { 
  6.         return _name; 
  7.     } 
  8.  
  9.     // 公共方式 
  10.     this.setName = function (value) { 
  11.         _name = value; 
  12.     } 
  13. var st = new Student('tom'); 
  14. st.setName('jerry'); 
  15. console.log(st.getName()); // => jerry:输出_name私有变量的值

注释规范

单行注释 ( // )

  • 单独一行://(双斜线)与注释文字之间保留一个空格
  • 在代码后面添加注释://(双斜线)与代码之间保留一个空格,并且//(双斜线)与注释文字之间保留一个空格。
  • 注释代码://(双斜线)与代码之间保留一个空格。

推荐 :

  1. // 调用了一个函数;1)单独在一行 
  2. setTitle(); 
  3.  
  4. var maxCount = 10; // 设置最大量;2)在代码后面注释 
  5.  
  6. // setName(); // 3)注释代码

多行注释 ( / 注释说明 / )

  • 若开始(/*和结束(*/)都在一行,推荐采用单行注释
  • 若至少三行注释时,第一行为/*,最后行为*/,其他行以*开始,并且注释文字与*保留一个空格。
    推荐 : /* * 代码执行到这里后会调用setTitle()函数 * setTitle():设置title的值 */ setTitle();复制代码

函数 ( 方法 ) 注释

函数(方法)注释也是多行注释的一种,但是包含了特殊的注释要求,参照 javadoc(百度百科)语法:

  1. /**  
  2. * 函数说明  
  3. * @关键字  
  4. */复制代码 

常用注释关键字

前端开发规范:命名规范、html规范、css规范、js规范

推荐 :

  1. /** 
  2.  - 合并Grid的行 
  3.  - @param grid {Ext.Grid.Panel} 需要合并的Grid 
  4.  - @param cols {Array} 需要合并列的Index(序号)数组;从0开始计数,序号也包含。 
  5.  - @param isAllSome {Boolean} :是否2个tr的cols必须完成一样才能进行合并。true:完成一样;false(默认):不完全一样 
  6.  - @return void 
  7.  - @author polk6 2015/07/21  
  8.  - @example 
  9.  - _________________                             _________________ 
  10.  - |  年龄 |  姓名 |                             |  年龄 |  姓名 | 
  11.  - -----------------      mergeCells(grid,[0])   ----------------- 
  12.  - |  18   |  张三 |              =>             |       |  张三 | 
  13.  - -----------------                             -  18   --------- 
  14.  - |  18   |  王五 |                             |       |  王五 | 
  15.  - -----------------                             ----------------- 
  16. */ 
  17. function mergeCells(grid, cols, isAllSome) { 
  18.     // Do Something 

HTML规范

文档规范

使用 HTML5 的文档声明类型 : <!DOCTYPE html>

  • DOCTYPE标签是一种标准通用标记语言的文档类型声明,它的目的是要告诉标准通用标记语言解析器,它应该使用什么样的文档类型定义(DTD)来解析文档。
  • 使用文档声明类型的作用是为了防止开启浏览器的怪异模式。
  • 没有DOCTYPE文档类型声明会开启浏览器的怪异模式,浏览器会按照自己的解析方式渲染页面,在不同的浏览器下面会有不同的样式。
  • 如果你的页面添加了<!DOCTYP>那么,那么就等同于开启了标准模式。浏览器会按照W3C标准解析渲染页面。

脚本加载

说到js和css的位置,大家应该都知道js放在下面,css放在上面。但是,如果你的项目只需要兼容ie10+或者只是在移动端访问,那么可以使用HTML5的新属性async,将脚本文件放在<head>内兼容老旧浏览器(IE9-)时:脚本引用写在 body 结束标签之前,并带上 async 属性。这虽然在老旧浏览器中不会异步加载脚本,但它只阻塞了 body 结束标签之前的 DOM 解析,这就大大降低了其阻塞影响。而在现代浏览器中:脚本将在 DOM 解析器发现 body 尾部的 script 标签才进行加载,此时加载属于异步加载,不会阻塞 CSSOM(但其执行仍发生在 CSSOM 之后)。综上所述,所有浏览器中推荐:

  1. <html> 
  2.   <head> 
  3.     <link rel="stylesheet" href="main.css"
  4.   </head> 
  5.   <body> 
  6.     <!-- body goes here --> 
  7.  
  8.     <script src="main.js" async></script> 
  9.   </body> 
  10. </html>

只兼容现代浏览器推荐:

  1. <html> 
  2.   <head> 
  3.     <link rel="stylesheet" href="main.css"
  4.     <script src="main.js" async></script> 
  5.   </head> 
  6.   <body> 
  7.     <!-- body goes here --> 
  8.   </body> 
  9. </html>

语义化

我们一直都在说语义化编程,语义化编程,但是在代码中很少有人完全使用正确的元素。使用语义化标签也是有理由SEO的。

语义化是指:根据元素其被创造出来时的初始意义来使用它。意思就是用正确的标签干正确的事,而不是只有div和span。

不推荐:

  1. <b>My page title</b> 
  2. <div class="top-navigation"
  3.   <div class="nav-item"><a href="#home">Home</a></div> 
  4.   <div class="nav-item"><a href="#news">News</a></div> 
  5.   <div class="nav-item"><a href="#about">About</a></div> 
  6. </div> 
  7.  
  8. <div class="news-page"
  9.   <div class="page-section news"
  10.     <div class="title">All news articles</div> 
  11.     <div class="news-article"
  12.       <h2>Bad article</h2> 
  13.       <div class="intro">Introduction sub-title</div> 
  14.       <div class="content">This is a very bad example for HTML semantics</div> 
  15.       <div class="article-side-notes">I think I'm more on the side and should not receive the main credits</div> 
  16.       <div class="article-foot-notes"
  17.         This article was created by David <div class="time">2014-01-01 00:00</div> 
  18.       </div> 
  19.     </div> 
  20.  
  21.     <div class="section-footer"
  22.       Related sections: Events, Public holidays 
  23.     </div> 
  24.   </div> 
  25. </div> 
  26.  
  27. <div class="page-footer"
  28.   Copyright 2014 
  29. </div>

推荐

  1. html 代码: 
  2. <!-- The page header should go into a header element --> 
  3. <header> 
  4.   <!-- As this title belongs to the page structure it's a heading and h1 should be used --> 
  5.   <h1>My page title</h1> 
  6. </header> 
  7.  
  8. <!-- All navigation should go into a nav element --> 
  9. <nav class="top-navigation"
  10.   <!-- A listing of elements should always go to UL (OL for ordered listings) --> 
  11.   <ul> 
  12.     <li class="nav-item"><a href="#home">Home</a></li> 
  13.     <li class="nav-item"><a href="#news">News</a></li> 
  14.     <li class="nav-item"><a href="#about">About</a></li> 
  15.   </ul> 
  16. </nav> 
  17.  
  18. <!-- The main part of the page should go into a main element (also use role="main" for accessibility) --> 
  19. <main class="news-page" role="main"
  20.   <!-- A section of a page should go into a section element. Divide a page into sections with semantic elements. --> 
  21.   <section class="page-section news"
  22.     <!-- A section header should go into a section element --> 
  23.     <header> 
  24.       <!-- As a page section belongs to the page structure heading elements should be used (in this case h2) --> 
  25.       <h2 class="title">All news articles</h2> 
  26.     </header> 
  27.  
  28.     <!-- If a section / module can be seen as an article (news article, blog entry, products teaser, any other 
  29.      re-usable module / section that can occur multiple times on a page) a article element should be used --> 
  30.     <article class="news-article"
  31.       <!-- An article can contain a header that contains the summary / introduction information of the article --> 
  32.       <header> 
  33.         <!-- As a article title does not belong to the overall page structure there should not be any heading tag! --> 
  34.         <div class="article-title">Good article</div> 
  35.         <!-- Small can optionally be used to reduce importance --> 
  36.         <small class="intro">Introduction sub-title</small> 
  37.       </header> 
  38.  
  39.       <!-- For the main content in a section or article there is no semantic element --> 
  40.       <div class="content"
  41.         <p>This is a good example for HTML semantics</p> 
  42.       </div> 
  43.       <!-- For content that is represented as side note or less important information in a given context use aside --> 
  44.       <aside class="article-side-notes"
  45.         <p>I think I'm more on the side and should not receive the main credits</p> 
  46.       </aside> 
  47.       <!-- Articles can also contain footers. If you have footnotes for an article place them into a footer element --> 
  48.       <footer class="article-foot-notes"
  49.         <!-- The time element can be used to annotate a timestamp. Use the datetime attribute to specify ISO time 
  50.          while the actual text in the time element can also be more human readable / relative --> 
  51.         <p>This article was created by David <time datetime="2014-01-01 00:00" class="time">1 month ago</time></p> 
  52.       </footer> 
  53.     </article> 
  54.  
  55.     <!-- In a section, footnotes or similar information can also go into a footer element --> 
  56.     <footer class="section-footer"
  57.       <p>Related sections: Events, Public holidays</p> 
  58.     </footer> 
  59.   </section
  60. </main> 
  61.  
  62. <!-- Your page footer should go into a global footer element --> 
  63. <footer class="page-footer"
  64.   Copyright 2014 
  65. </footer>

alt标签不为空

<img>标签的 alt 属性指定了替代文本,用于在图像无法显示或者用户禁用图像显示时,代替图像显示在浏览器中的内容。假设由于下列原因用户无法查看图像,alt 属性可以为图像提供替代的信息:

  • 网速太慢
  • src 属性中的错误
  • 浏览器禁用图像
  • 用户使用的是屏幕阅读器

从SEO角度考虑,浏览器的爬虫爬不到图片的内容,所以我们要有文字告诉爬虫图片的内容

结构、表现、行为三者分离

尽量在文档和模板中只包含结构性的 HTML;而将所有表现代码,移入样式表中;将所有动作行为,移入脚本之中。在此之外,为使得它们之间的联系尽可能的小,在文档和模板中也尽量少地引入样式和脚本文件。建议:

  • 不使用超过一到两张样式表
  • 不使用超过一到两个脚本(学会用合并脚本)
  • 不使用行内样式(<style>.no-good {}</style>)
  • 不在元素上使用 style 属性(<hr style="border-top: 5px solid black">)
  • 不使用行内脚本(<script>alert('no good')</script>)
  • 不使用表象元素(i.e. <b>, <u>, <center>, <font>, <b>)
  • 不使用表象 class 名(i.e. red, left, center)

HTML只关注内容

  • HTML只显示展示内容信息
  • 不要引入一些特定的 HTML 结构来解决一些视觉设计问题
  • 不要将img元素当做专门用来做视觉设计的元素
  • 样式上的问题应该使用css解决

不推荐:

  1. <!-- We should not introduce an additional element just to solve a design problem  --> 
  2. <span class="text-box"
  3.   <span class="square"></span> 
  4.   See the square next to me? 
  5. </span> 
  6. css 代码: 
  7. .text-box > .square { 
  8.   display: inline-block; 
  9.   width: 1rem; 
  10.   height: 1rem; 
  11.   background-color: red; 

推荐

  1. html 代码: 
  2. <!-- That's clean markup! --> 
  3. <span class="text-box"
  4.   See the square next to me? 
  5. </span> 
  6. css 代码: 
  7. /* We use a :before pseudo element to solve the design problem of placing a colored square in front of the text content */ 
  8. .text-box:before { 
  9.   content: ""
  10.   display: inline-block; 
  11.   width: 1rem; 
  12.   height: 1rem; 
  13.   background-color: red; 

图片和 SVG 图形能被引入到 HTML 中的唯一理由是它们呈现出了与内容相关的一些信息。

不推荐

  1. html 代码: 
  2. <!-- Content images should never be used for design elements!  --> 
  3. <span class="text-box"
  4.   <img src="square.svg" alt="Square" /> 
  5.   See the square next to me? 
  6. </span> 

推荐

  1. html 代码: 
  2. <!-- That's clean markup! --> 
  3. <span class="text-box"
  4.   See the square next to me? 
  5. </span> 
  6. css 代码: 
  7. /* We use a :before pseudo element with a background image to solve the problem */ 
  8. .text-box:before { 
  9.   content: ""
  10.   display: inline-block; 
  11.   width: 1rem; 
  12.   height: 1rem; 
  13.   background: url(square.svg) no-repeat; 
  14.   background-size: 100%; 

js规范

避免全局命名空间污染

防止全局命名空间被污染,我们通常的做法是将代码包裹成一个 IIFE(Immediately-Invoked Function Expression),创建独立隔绝的定义域。也使得内存在执行完后立即释放。

IIFE 还可确保你的代码不会轻易被其它全局命名空间里的代码所修改(i.e. 第三方库,window 引用,被覆盖的未定义的关键字等等)。不推荐:

  1. var x = 10, 
  2.     y = 100; 
  3.  
  4. // Declaring variables in the global scope is resulting in global scope pollution. All variables declared like this 
  5. // will be stored in the window object. This is very unclean and needs to be avoided. 
  6. console.log(window.x + ' ' + window.y);

推荐

  1. // We declare a IIFE and pass parameters into the function that we will use from the global space 
  2. (function(log, w, undefined){ 
  3.   'use strict'
  4.  
  5.   var x = 10, 
  6.       y = 100; 
  7.  
  8.   // Will output 'true true' 
  9.   log((w.x === undefined) + ' ' + (w.y === undefined)); 
  10.  
  11. }(window.console.log, window)); 

推荐的IIFE写法:

  1. (function(){ 
  2.   'use strict'
  3.  
  4.   // Code goes here 
  5.  
  6. }());

如果你想引用全局变量或者是外层 IIFE 的变量,可以通过下列方式传参:

  1. (function($, w, d){ 
  2.   'use strict'
  3.  
  4.   $(function() { 
  5.     w.alert(d.querySelectorAll('div').length); 
  6.   }); 
  7. }(jQuery, window, document));复制代码 

严格模式

ECMAScript 5 严格模式可在整个脚本或独个方法内被激活。它对应不同的 javascript 语境会做更加严格的错误检查。严格模式也确保了 javascript 代码更加的健壮,运行的也更加快速。

严格模式会阻止使用在未来很可能被引入的预留关键字。

你应该在你的脚本中启用严格模式,最好是在独立的 IIFE 中应用它。避免在你的脚本第一行使用它而导致你的所有脚本都启动了严格模式,这有可能会引发一些第三方类库的问题。

变量声明

总是使用 var 来声明变量。如不指定 var,变量将被隐式地声明为全局变量,例如

  1. var a = b = 0; //b会被隐式的创建为全局变量复制代码 

所以,请总是使用 var 来声明变量,并且使用单var模式(将所有的变量在函数最前面只使用一个var定义)。例如:

  1. (function (){ 
  2.   'use strict' 
  3.   var a = 0, 
  4.       b = 0, 
  5.       c = 0, 
  6.       i, 
  7.       j, 
  8.       myObject(); 
  9. }())

采用严格模式带来的好处是,当你手误输入错误的变量名时,它可以通过报错信息来帮助你定位错误出处。

js声明提前

javascript会自动将函数作用域内的变量和方法的定义提前(只是提前声明,赋值还是在原处)例如:

  1. (function(log){ 
  2.   'use strict'
  3.  
  4.   var a = 10; 
  5.  
  6.   for(var i = 0; i < a; i++) { 
  7.     var b = i * i; 
  8.     log(b); 
  9.   } 
  10.  
  11.   if(a === 10) { 
  12.     var f = function() { 
  13.       log(a); 
  14.     }; 
  15.     f(); 
  16.   } 
  17.  
  18.   function x() { 
  19.     log('Mr. X!'); 
  20.   } 
  21.   x(); 
  22.  
  23. }(window.console.log)); 

提升后的js

  1. (function(log){ 
  2.   'use strict'
  3.   // All variables used in the closure will be hoisted to the top of the function 
  4.   var a, 
  5.       i, 
  6.       b, 
  7.       f; 
  8.   // All functions in the closure will be hoisted to the top 
  9.   function x() { 
  10.     log('Mr. X!'); 
  11.   } 
  12.  
  13.   a = 10; 
  14.  
  15.   for(i = 0; i < a; i++) { 
  16.     b = i * i; 
  17.     log(b); 
  18.   } 
  19.  
  20.   if(a === 10) { 
  21.     // Function assignments will only result in hoisted variables but the function body will not be hoisted 
  22.     // Only by using a real function declaration the whole function will be hoisted with its body 
  23.     f = function() { 
  24.       log(a); 
  25.     }; 
  26.     f(); 
  27.   } 
  28.  
  29.   x(); 
  30.  
  31. }(window.console.log)); 

使用严格等

总是使用 === 精确的比较操作符,避免在判断的过程中,由 JavaScript 的强制类型转换所造成的困扰。例如:

 
  1. (function(log){ 
  2.   'use strict'
  3.  
  4.   log('0' == 0); // true 
  5.   log('' == false); // true 
  6.   log('1' == true); // true 
  7.   log(null == undefined); // true 
  8.  
  9.   var x = { 
  10.     valueOf: function() { 
  11.       return 'X'
  12.     } 
  13.   }; 
  14.  
  15.   log(x == 'X'); 
  16.  
  17. }(window.console.log));

等同== 和严格等===的区别

  • ==, 两边值类型不同的时候,要先进行类型转换,再比较。
  • ===,不做类型转换,类型不同的一定不等。

==等同操作符

  • 如果两个值具有相同类型,会进行===比较,返回===的比较值
  • 如果两个值不具有相同类型,也有可能返回true
  • 如果一个值是null另一个值是undefined,返回true
  • 如果一个值是string另个是number,会把string转换成number再进行比较
  • 如果一个值是true,会把它转成1再比较,false会转成0
 
  1. console.log( false == null )      // false 
  2. console.log( false == undefined ) // false 
  3. console.log( false == 0 )         // true 
  4. console.log( false == '' )        // true 
  5. console.log( false == NaN )       // false 
  6.  
  7. console.log( null == undefined ) // true 
  8. console.log( null == 0 )         // false 
  9. console.log( null == '' )        // false 
  10. console.log( null == NaN )       // false 
  11.  
  12. console.log( undefined == 0)   // false 
  13. console.log( undefined == '')  // false 
  14. console.log( undefined == NaN) // false 
  15.  
  16. console.log( 0 == '' )  // true 
  17. console.log( 0 == NaN ) // false 

总结一下==

  • false 除了和自身比较为 true 外,和 0,"" 比较也为 true
  • null 只和 undefined 比较时为 true, 反过来 undefined 也仅和 null 比较为 true,没有第二个
  • 0 除了和 false 比较为 true,还有空字符串 ''" 和空数组 []
  • 空字符串 '' 除了和 false 比较为 true,还有一个数字 0

==, >, <, +, -, ... 这些操作符所造成的隐式类型转换都是无副作用的,它不会改变变量本身保存的值。,但是,如果你覆写某个对象的 valueOf/toString的话,==就会产生副作用.

例如:

  1. Array.prototype.valueOf = function() { 
  2.   this[0]++; 
  3.   return this; 
  4. var x = [1, 2, 3]; 
  5. x == 0; 
  6. console.log(x);   // [2, 2, 3]复制代码 

===操作符:

  • 要是两个值类型不同,返回false
  • 要是两个值都是number类型,并且数值相同,返回true
  • 要是两个值都是stirng,并且两个值的String内容相同,返回true
  • 要是两个值都是true或者都是false,返回true
  • 要是两个值都是指向相同的Object,Arraya或者function,返回true
  • 要是两个值都是null或者都是undefined,返回true

真假判断

  • js中以下内容为假:
  • false
  • null
  • undefined
  • 0
  • '' (空字符串)
  • NaN

设置默认参数

辑操作符 || 和 && 也可被用来返回布尔值。如果操作对象为非布尔对象,那每个表达式将会被自左向右地做真假判断。基于此操作,最终总有一个表达式被返回回来。这在变量赋值时,是可以用来简化你的代码的。例如:如果x不存在且y不存在,x=1;如果x存在y存在,x = y

  1. if(!x) { 
  2.   if(!y) { 
  3.     x = 1; 
  4.   } else { 
  5.     x = y; 
  6.   } 
  7. }

等同于:

 x = x || y || 1;复制代码

这一小技巧经常用来给方法设定默认的参数。

  1. (function(log){ 
  2.   'use strict'
  3.  
  4.   function multiply(a, b) { 
  5.     a = a || 1; 
  6.     b = b || 1; 
  7.  
  8.     log('Result ' + a * b); 
  9.   } 
  10.  
  11.   multiply(); // Result 1 
  12.   multiply(10); // Result 10 
  13.   multiply(3, NaN); // Result 3 
  14.   multiply(9, 5); // Result 45 
  15.  
  16. }(window.console.log));

不使用eval()函数

就如eval的字面意思来说,恶魔,使用eval()函数会带来安全隐患。eval()函数的作用是返回任意字符串,当作js代码来处理。

this关键字

只在对象构造器、方法和在设定的闭包中使用 this 关键字。this 的语义在此有些误导。它时而指向全局对象(大多数时),时而指向调用者的定义域(在 eval 中),时而指向 DOM 树中的某一节点(当用事件处理绑定到 HTML 属性上时),时而指向一个新创建的对象(在构造器中),还时而指向其它的一些对象(如果函数被 call() 和 apply() 执行和调用时)。

正因为它是如此容易地被搞错,请限制它的使用场景:

  • 在构造函数中
  • 在对象的方法中(包括由此创建出的闭包内)

首选函数式风格

函数式编程让你可以简化代码并缩减维护成本,因为它容易复用,又适当地解耦和更少的依赖。

接下来的例子中,在一组数字求和的同一问题上,比较了两种解决方案。第一个例子是经典的程序处理,而第二个例子则是采用了函数式编程和 ECMA Script 5.1 的数组方法。不推荐

  1. (function(log){ 
  2.   'use strict'
  3.  
  4.   var arr = [10, 3, 7, 9, 100, 20], 
  5.       sum = 0, 
  6.       i; 
  7.  
  8.  
  9.   for(i = 0; i < arr.length; i++) { 
  10.     sum += arr[i]; 
  11.   } 
  12.  
  13.   log('The sum of array ' + arr + ' is: ' + sum
  14.  
  15. }(window.console.log));

推荐(函数式编程):

  1. (function(log){ 
  2.   'use strict'
  3.  
  4.   var arr = [10, 3, 7, 9, 100, 20]; 
  5.  
  6.   var sum = arr.reduce(function(prevValue, currentValue) { 
  7.     return prevValue + currentValue; 
  8.   }, 0); 
  9.  
  10.   log('The sum of array ' + arr + ' is: ' + sum); 
  11.  
  12. }(window.console.log));

修改内建对象的原型链

修改内建的诸如 Object.prototype 和 Array.prototype 是被严厉禁止的。修改其它的内建对象比如 Function.prototype,虽危害没那么大,但始终还是会导致在开发过程中难以 debug 的问题,应当也要避免。

三元条件判断(if 的快捷方法)

用三元操作符分配或返回语句。在比较简单的情况下使用,避免在复杂的情况下使用。没人愿意用 10 行三元操作符把自己的脑子绕晕。不推荐:

  1. if(x === 10) { 
  2.   return 'valid'
  3. else { 
  4.   return 'invalid'

推荐:

  1. return x === 10 ? 'valid' : 'invalid' 

JSHint

在js规范中,有很多规范都是样式上的规范而不是逻辑上的规范,比如尽量使用===而不是==,我们可以使用JSHint或者JSLint,Javascript代码验证工具,这种工具可以检查你的代码并提供相关的代码改进意见。我个人使用的是JSHint,所以就以这个为例

webstorm内置JSHint

对于ws爱好者来说,我没有用过其他的编译器,ws基本上能满足你的所有需求(最新的ws集成了vue)。在Settings => language & frameworks => JavaScript => Code Quality Tolls => JSHint

前端开发规范:命名规范、html规范、css规范、js规范

 

webstorm中的jshint

这些规范都是什么意思呢,这里列出一些常用的,剩下的大家可以参考官方文档

前端开发规范:命名规范、html规范、css规范、js规范

 

 

css规范

id和class的命名

ID和class的名称总是使用可以反应元素目的和用途的名称,或其他通用的名称,代替表象和晦涩难懂的名称不推荐 :

  1. .fw-800 { 
  2.   font-weight: 800; 
  3.  
  4. .red { 
  5.   color: red; 
  6. }

推荐 :

  1. .heavy { 
  2.   font-weight: 800; 
  3.  
  4. .important { 
  5.   color: red; 
  6. }

合理的使用ID

一般情况下ID不应该被用于样式,并且ID的权重很高,所以不使用ID解决样式的问题,而是使用class不推荐:

  1. #content .title { 
  2.   font-size: 2em; 

推荐:

  1. .content .title { 
  2.   font-size: 2em; 

css选择器中避免使用标签名

从结构、表现、行为分离的原则来看,应该尽量避免css中出现HTML标签,并且在css选择器中出现标签名会存在潜在的问题。

使用子选择器

很多前端开发人员写选择器链的时候不使用 直接子选择器(注:直接子选择器和后代选择器的区别)。有时,这可能会导致疼痛的设计问题并且有时候可能会很耗性能。然而,在任何情况下,这是一个非常不好的做法。如果你不写很通用的,需要匹配到DOM末端的选择器, 你应该总是考虑直接子选择器。不推荐:

  1. .content .title { 
  2.   font-size: 2rem; 

推荐

  1. .content > .title { 
  2.   font-size: 2rem; 

尽量使用缩写属性

尽量使用缩写属性对于代码效率和可读性是很有用的,比如font属性。不推荐:

  1. border-top-style: none; 
  2. font-family: palatino, georgia, serif; 
  3. font-size: 100%; 
  4. line-height: 1.6; 
  5. padding-bottom: 2em; 
  6. padding-left: 1em; 
  7. padding-right: 1em; 
  8. padding-top: 0;

推荐:

  1. border-top: 0; 
  2. font: 100%/1.6 palatino, georgia, serif; 
  3. padding: 0 1em 2em; 

0后面不带单位

省略0后面的单位,不推荐:

  1. padding-bottom: 0px; 
  2. margin: 0em;

推荐:

  1. padding-bottom: 0; 
  2. margin: 0;

属性格式

  • 为了保证一致性和可扩展性,每个声明应该用分号结束,每个声明换行。
  • 属性名的冒号后使用一个空格。出于一致性的原因,
    属性和值(但属性和冒号之间没有空格)的之间始终使用一个空格。
  • 每个选择器和属性声明总是使用新的一行。
  • 属性选择器或属性值用双引号(””),而不是单引号(”)括起来。
  • URI值(url())不要使用引号。

作为最佳实践,我们应该遵循以下顺序(应该按照下表的顺序):

结构性属性:

  1. display
  2. position, left, top, right etc.
  3. overflow, float, clear etc.
  4. margin, padding

表现性属性:

  • background, border etc.
  • font, text

不推荐:

  1. .box { 
  2.  font-family: 'Arial', sans-serif; 
  3.  border: 3px solid #ddd; 
  4.  left: 30%; 
  5.  position: absolute
  6.  text-transform: uppercase; 
  7.  background-color: #eee; 
  8.  right: 30%; 
  9.  isplay: block; 
  10.  font-size: 1.5rem; 
  11.  overflow: hidden; 
  12.  padding: 1em; 
  13.  margin: 1em;

推荐:

  1. .box { 
  2.   display: block; 
  3.   position: absolute
  4.   left: 30%; 
  5.   right: 30%; 
  6.   overflow: hidden; 
  7.   margin: 1em; 
  8.   padding: 1em; 
  9.   background-color: #eee; 
  10.   border: 3px solid #ddd; 
  11.   font-family: 'Arial', sans-serif; 
  12.   font-size: 1.5rem; 
  13.   text-transform: uppercase; 

 

责任编辑:庞桂玉 来源: 今日头条
相关推荐

2016-09-29 15:19:04

HTMLCSSWeb

2009-08-03 16:57:42

ASP.NET编程规范

2016-05-17 14:03:07

Android命名解决方案

2022-08-02 07:48:06

容器镜像版本

2017-07-20 11:11:39

前端CSS书写规范

2020-11-05 10:20:54

前端编码规范安全漏洞

2010-09-07 15:53:02

CSS规范化

2011-11-01 10:12:09

Web

2023-11-22 08:00:56

Go命名规范

2011-05-13 16:53:58

JavaScript

2010-08-31 13:32:12

CSS

2022-12-28 08:16:30

CSS新规范样式

2010-08-24 15:31:51

DIVCSS

2010-09-02 09:32:09

DIV CSS

2010-04-30 14:05:55

Mocha BSM运维管理摩卡软件

2009-08-27 16:30:08

C#编程命名规范

2009-08-19 15:24:30

.NET命名规范

2009-08-21 08:52:40

C#语言命名

2009-08-13 13:38:30

C#命名规范

2009-08-03 17:07:13

ASP.NET编程规范
点赞
收藏

51CTO技术栈公众号