本文转自我司的编码规范~

====

引言

将要叙述的这些原则旨对javascript开发的风格做指导,并非指定性的规则需绝对服从。如果需要找出一条必须遵循的原则,应该是保持代码的一致性和风格统一

除去对代码的可读性、可维护性有益外,同时可以减少很多代码提交解决冲突合并时产生的不必要的麻烦。

代码风格

空格

  • 不要混用tab 和 空格.
  • 在开始项目编码之前制定缩进规则,使用空格缩进还是tab缩进,并且严格贯彻下去。
    • 建议统一使用空格缩进(2spaces),使用编辑器的设置tab键为空格空进以强制执行。
  • 如果你的编辑器支持设置“显示隐藏字符”的话,建议打开它。好处在于:
    • 强制代码格式统一
    • 去除行尾空字符
    • 去除空行空字符Eliminating blank line whitespace
    • 代码提交比较差异时更方便阅读

Syntax美化

Syntax美化包括空格的规则、换行的规则,以及其他语法层面上的书写格式,以方便阅读为准。可以使用编辑器的格式化插件来达到格式美化的目的,项目开发人员需要统一插件格式的规则,以避免提交代码时格式不统一而产生的不必要的麻烦。

[插件https://github.com/akalongman/sublimetext-codeformatter|SublimeText Code Formatter](https://github.com/akalongman/sublimetext-codeformatter|SublimeText Code Formatter)

语言规则

变量

  • 声明变量时应该使用var。不这样做会得到全局变量,从而污染了全局命名空间。
  • 使用一个 var 以及新行声明多个变量,缩进4个空格
  • 最后再声明未赋值的变量,当以后你想给一个依赖之前已赋值变量的变量时很有用。
  • 不一定严格按照只是用一个var声明变量的规则,可以按照变量的相关性分组声明。
     var items = getItems(),
goSportsTeam = true,
dragonball,
length,
i;
  • 在作用域顶部声明变量,避免变量声明和赋值引起的相关问题。
     // bad
function() {
test();
console.log('doing stuff..'); //..other stuff.. var name = getName(); if (name === 'test') {
return false;
} return name;
} // good
function() {
var name = getName(); test();
console.log('doing stuff..'); //..other stuff.. if (name === 'test') {
return false;
} return name;
} // bad
function() {
var name = getName(); if (!arguments.length) {
return false;
} return true;
} // good
function() {
if (!arguments.length) {
return false;
} var name = getName(); return true;
}

函数

  • 不要在块内定义functions。
//Do not do this:

if (x) {
function foo() {}
}
//Do this
var foo;
if(x) {
foo = function(){};
}
  • 函数表达式:
// 匿名函数表达式
var anonymous = function() {
return true;
}; // 有名函数表达式
var named = function named() {
return true;
}; // 立即调用函数表达式
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
  • 绝对不要把参数命名为 arguments, 这将会逾越函数作用域内传过来的 arguments 对象.
// bad
function nope(name, options, arguments) {
// ...stuff...
} // good
function yup(name, options, args) {
// ...stuff...
}

字符串

  • 对字符串使用单引号 '
// bad
var name = "Bob Parr"; // good
var name = 'Bob Parr'; // bad
var fullName = "Bob " + this.lastName; // good
var fullName = 'Bob ' + this.lastName;
  • 超过80个字符的字符串应该使用字符串连接换行

  • 果过度使用,长字符串连接可能会对性能有影响.

// bad
var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'; // bad
var errorMessage = 'This is a super long error that \
was thrown because of Batman. \
When you stop to think about \
how Batman had anything to do \
with this, you would get nowhere \
fast.'; // good
var errorMessage = 'This is a super long error that ' +
'was thrown because of Batman.' +
'When you stop to think about ' +
'how Batman had anything to do ' +
'with this, you would get nowhere ' +
'fast.';

逗号

  • 不要将逗号放前面
// bad
var once
, upon
, aTime; // good
var once,
upon,
aTime; // bad
var hero = {
firstName: 'Bob'
, lastName: 'Parr'
, heroName: 'Mr. Incredible'
, superPower: 'strength'
}; // good
var hero = {
firstName: 'Bob',
lastName: 'Parr',
heroName: 'Mr. Incredible',
superPower: 'strength'
};
  • 不要加多余的逗号
// bad
var hero = {
firstName: 'Kevin',
lastName: 'Flynn',
}; var heroes = [
'Batman',
'Superman',
]; // good
var hero = {
firstName: 'Kevin',
lastName: 'Flynn'
}; var heroes = [
'Batman',
'Superman'
];

分号

  • 语句结束一定要加分号
// bad
(function() {
var name = 'Skywalker'
return name
})() // good
(function() {
var name = 'Skywalker';
return name;
})(); // good
;(function() {
var name = 'Skywalker';
return name;
})();

类型转换

  • 在语句的开始执行类型转换.
  • 字符串:
//  => this.reviewScore = 9;

// bad
var totalScore = this.reviewScore + ''; // good
var totalScore = '' + this.reviewScore;
  • 对数字使用 parseInt 并且总是带上类型转换的基数.
var inputValue = '4';

// bad
var val = new Number(inputValue); // bad
var val = +inputValue; // bad
var val = inputValue >> 0; // bad
var val = parseInt(inputValue); // good
var val = Number(inputValue); // good
var val = parseInt(inputValue, 10); // with caution
/**
* parseInt was the reason my code was slow.
* Bitshifting the String to coerce it to a
* Number made it a lot faster. But it reduces the readability.
*/
var val = inputValue >> 0;

相等性

  • 优先选择严格的 “ === ” 做相等性判断,但是当检查是否是undefined 或者 null时, 可以使用“ == ”。

命名规则

  • 避免单个字符名,让你的变量名有描述意义。变量一般用名词, 函数一般使用动词,若函数返回boolean则可以用is或者has开头。常量使用全大写以下划线链接。
//good
var PI = 3.1415926;
// bad
function q() {
// ...stuff...
} // good
function query() {
// ..stuff..
}
  • 当命名对象、函数和实例时使用驼峰命名规则
// bad
var OBJEcttsssss = {};
var this_is_my_object = {};
var this-is-my-object = {};
function c() {};
var u = new user({
name: 'Bob Parr'
}); // good
var thisIsMyObject = {};
function thisIsMyFunction() {};
var user = new User({
name: 'Bob Parr'
});
  • 当命名构造函数或类时使用驼峰式大写
// bad
function user(options) {
this.name = options.name;
} var bad = new user({
name: 'nope'
}); // good
function User(options) {
this.name = options.name;
} var good = new User({
name: 'yup'
});
  • 命名私有属性时前面加个下划线
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda'; // good
this._firstName = 'Panda';
  • 当保存对 this 的引用时使用 _this
// bad
function() {
var self = this;
return function() {
console.log(self);
};
} // bad
function() {
var that = this;
return function() {
console.log(that);
};
} // good
function() {
var _this = this;
return function() {
console.log(_this);
};
}

其他

  • Prefer this.foo = null than delete this.foo
  • 小心使用switch语句
  • 不要轻易扩展修改builtin类型的行为
  • 谨慎使用保留字作为object属性名(已经吃过亏了)
  • 避免使用with

参考资料

编写一致的符合习惯的javascript的更多相关文章

  1. dart --- 更符合程序员编程习惯的javascript替代者

    dart是google在2011年推出的一门语言,提供较为丰富的lib,并支持将代码转变为javascript,其demo code 和 demo app 也是以web前端代码来展示的. 其语言特性较 ...

  2. JavaScript网站设计实践(四)编写about.html页面,利用JavaScript和DOM,选择性的显示和隐藏DIV元素

    一.现在我们在网站设计(三)的基础上,来编写about.html页面. 这个页面要用到的知识点是利用JavaScript和DOM实现选择性地显示和隐藏某些DIV about.html页面在前面我们为了 ...

  3. 编写更加稳定/可读的javascript代码

    每个人都有自己的编程风格,也无可避免的要去感受别人的编程风格--修改别人的代码."修改别人的代码"对于我们来说的一件很痛苦的事情.因为有些代码并不是那么容易阅读.可维护的,让另一个 ...

  4. 使用AmplifyJS和JQuery编写更好更优雅的javascript事件处理代码

    事件(或消息)是一种经常使用的软件设计模式.可以减少消息处理者和消息公布者的之间的耦合,比方J2EE里面的JMS规范.设计模式中的观察者模式(也叫公布/订阅模式).这对于javascript代码相同适 ...

  5. 读《编写高质量代码:改善JavaScript程序的188个建议》1

    建议3:减少全局变量污染 定义全局变量有3种方式: ❑在任何函数外面直接执行var语句. var f='value'; ❑直接添加一个属性到全局对象上.全局对象是所有全局变量的容器.在Web浏览器中, ...

  6. 编写自己的代码库(javascript常用实例的实现与封装)[转]

    1.前言 因为公司最近项目比较忙,没那么多空余的事件写文章了,所以这篇文章晚了几天发布.但是这也没什么关系,不过该来的,总是会来的.好了,其他的不多说的,大家在开发的时候应该知道,有很多常见的实例操作 ...

  7. 《编写高质量代码:改善JavaScript程序的188个建议》学习小记(二)

    建议3:减少全局变量污染 1.把多个全局变量都追加在一个名称空间下,将显著降低与其他应用程序产生冲突的概率,应用程序也会变得更容易阅读. var My = {}; My.name = { " ...

  8. 读《编写高质量代码:改善JavaScript程序的188个建议》2

  9. 编写自己的代码库(javascript常用实例的实现与封装)

    https://segmentfault.com/a/1190000010225928

随机推荐

  1. 前后台交互(打开前端页面,不传递任何数据,发送ajax请求)

    1.打开前端,不传递任何数据 <script src="./jquery.min.js"></script> <script> $(docume ...

  2. Netty 零拷贝(三)Netty 对零拷贝的改进

    Netty 零拷贝(三)Netty 对零拷贝的改进 Netty 系列目录 (https://www.cnblogs.com/binarylei/p/10117436.html) Netty 的&quo ...

  3. smrtlink

    SMRT Link is the web-based end-to-end workflow manager for the Sequel™ System. It includes software ...

  4. 浅析10种常见的黑帽seo手法

    虽然博主并不认同黑帽seo手法,但是一些常见的黑帽手法还是需要了解的,增加自己对黑帽的认知,也可以在自己优化网站时适时的规避开这些黑帽手法,从而避免自己的网站被搜索引擎惩罚.好了,话不多说,下面进入今 ...

  5. tp5月统计的bug

    月统计求和时 本月第一天没有统计到

  6. Java 继承关系中:static,构造函数,成员变量的加载顺序

    首先看下面的例子: package simple.demo; /** * @author Administrator * @date 2019/01/03 */ public class ClassA ...

  7. JavaNIO学习一

    文章来源:http://cucaracha.iteye.com/blog/2041847 对文件来说,可能最常用的操作就是创建.读取和写出.NIO.2 提供了丰富的方法来完成这些任务.本文从简单的小文 ...

  8. momery

    reg [7:0] moma [255:0] ;//定义一个位宽为8,浓度为什么256的memory. parameter wordsize = 8; parameter memsize = 256; ...

  9. NSDictionary NSMutableDictionary NSSet NSMutableSet

    //description只是返回了一个字符串 //    [person description]; //        //如果想要打印需要NSLog //    NSLog(@"%@& ...

  10. Fig 7.2.4 & Fig 7.3.2

    Fig 7.2.4 \documentclass[varwidth=true, border=2pt]{standalone} \usepackage{tkz-euclide} \begin{docu ...