javascript 代码风格

更新日期: 2015-12-12 阅读次数: 5696 分类: Javascript

"For the past 33 years, I have looked in the mirror every morning and asked myself: 'If today were the last day of my life, would I want to do what I am about to do today?' And whenever the answer has been 'No' for too many days in a row, I know I need to change something." - Steve Jobs

参考

jslint

sudo npm install -g jslint

add this line to .bashrc: alias jslint="~/.npm/jslint/0.1.9/package/bin/jslint.js"

Chaining Methods 每行一个 method

d3.select("body")
  .append("p")
  .text("New paragraph!");

命名规则

In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, CONSTANT_VALUES_LIKE_THIS, foo.namespaceNamesLikeThis.bar, and filenameslikethis.js.

从 AngularJS 的代码来看,Google 遵守的就是这套命名规范。采用单词首字母大写的好 处是: js 没有 class 关键字,如果采用下划线的命名法,无法分辨到底一个变量名字 到底是 function 还是 class 名。

关于缩进

使用 TAB 还是四个空格、两个空格好?

I prefer tabs:

  • They're a character specifically meant for indentation
  • They allow developers with different preferences in indentation size to change how it's the code looks without changing the code (separation of data and presentation for the proverbial win!)
  • It's impossible to half-indent something with tabs. So when you copy code from some website that used 3 spaces into your 4-space indented file, you don't have to deal with misalignment.

参考 Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever? [closed]

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式