javascript_style_rules.rst 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  1. Javascript风格规范
  2. =====================
  3. 命名
  4. --------------
  5. 通常来说,使用 ``functionNamesLikeThis`` , ``variableNamesLikeThis`` , ``ClassNamesLikeThis`` , ``EnumNamesLikeThis`` , ``methodNamesLikeThis`` , ``CONSTANT_VALUES_LIKE_THIS`` , ``foo.namespaceNamesLikeThis.bar`` 和 ``filenameslikethis.js`` 这种格式的命名方式。
  6. 属性和方法
  7. ~~~~~~~~~~~~~~
  8. * *私有* 属性和方法应该以下划线开头命名。
  9. * *保护* 属性和方法应该以无下划线开头命名(像公共属性和方法一样)。
  10. 了解更多关于私有成员和保护成员的信息,请阅读 `可见性 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Visibility__private_and_protected_fields_>`_ 部分。
  11. 方法和函数参数
  12. ~~~~~~~~~~~~~~~~~
  13. 可选函数参数以 ``opt_`` 开头。
  14. 参数数目可变的函数应该具有以 ``var_args`` 命名的最后一个参数。你可能不会在代码里引用 ``var_args`` ;使用 ``arguments`` 对象。
  15. 可选参数和数目可变的参数也可以在注释 ``@param`` 中指定。尽管这两种惯例都被编译器接受,但更加推荐两者一起使用。
  16. getter和setter
  17. ~~~~~~~~~~~~~~~~~
  18. EcmaScript 5 不鼓励使用属性的getter和setter。然而,如果使用它们,那么getter就不要改变属性的可见状态。
  19. ::
  20. /**
  21. *错误--不要这样做.
  22. */
  23. var foo = { get next() { return this.nextId++; } };
  24. };
  25. 存取函数
  26. ~~~~~~~~
  27. 属性的getter和setter方法不是必需的。然而,如果使用它们,那么读取方法必须以 ``getFoo()`` 命名,并且写入方法必须以 ``setFoo(value)`` 命名。(对于布尔型的读取方法,也可以使用 ``isFoo()`` ,并且这样往往听起来更自然。)
  28. 命名空间
  29. ~~~~~~~~
  30. JavaScript没有原生的对封装和命名空间的支持。
  31. 全局命名冲突难以调试,并且当两个项目尝试整合的时候可能引起棘手的问题。为了能共享共用的JavaScript代码,我们采用一些约定来避免冲突。
  32. 为全局代码使用命名空间
  33. #########################
  34. 在全局范围内 *总是* 使用唯一的项目或库相关的伪命名空间进行前缀标识。如果你正在进行“Project Sloth”项目,一个合理的伪命名空间为 ``sloth.*`` 。
  35. ::
  36. var sloth = {};
  37. sloth.sleep = function() {
  38. ...
  39. };
  40. 很多JavaScript库,包括 `the Closure Library <https://developers.google.com/closure/library/?csw=1>`_ 和 `Dojo toolkit <http://dojotoolkit.org/>`_ 给你高级功能来声明命名空间。保持你的命名空间声明一致。
  41. ::
  42. goog.provide('sloth');
  43. sloth.sleep = function() {
  44. ...
  45. };
  46. 尊重命名空间所有权
  47. #####################
  48. 当选择一个子命名空间的时候,确保父命名空间知道你在做什么。如果你开始了一个为sloths创建hats的项目,确保Sloth这一组命名空间知道你在使用 ``sloth.hats`` 。
  49. 外部代码和内部代码使用不同的命名空间
  50. ########################################
  51. “外部代码”指的是来自你的代码库外并独立编译的代码。内部名称和外部名称应该严格区分开。如果你正在使用一个能调用 ``foo.hats.*`` 中的东西的外部库,你的内部代码不应该定义 ``foo.hats.*`` 中的所有符号,因为如果其他团队定义新符号就会把它打破。
  52. ::
  53. foo.require('foo.hats');
  54. /**
  55. *错误--不要这样做。
  56. * @constructor
  57. * @extends {foo.hats.RoundHat}
  58. */
  59. foo.hats.BowlerHat = function() {
  60. };
  61. 如果你在外部命名空间中需要定义新的API,那么你应该明确地导出且仅导出公共的API函数。为了一致性和编译器更好的优化你的内部代码,你的内部代码应该使用内部API的内部名称调用它们。
  62. ::
  63. foo.provide('googleyhats.BowlerHat');
  64. foo.require('foo.hats');
  65. /**
  66. * @constructor
  67. * @extends {foo.hats.RoundHat}
  68. */
  69. googleyhats.BowlerHat = function() {
  70. ...
  71. };
  72. goog.exportSymbol('foo.hats.BowlerHat', googleyhats.BowlerHat);
  73. 为长类型的名称提供别名提高可读性
  74. ###################################
  75. 如果对完全合格的类型使用本地别名可以提高可读性,那么就这样做。本地别名的名称应该符合类型的最后一部分。
  76. ::
  77. /**
  78. * @constructor
  79. */
  80. some.long.namespace.MyClass = function() {
  81. };
  82. /**
  83. * @param {some.long.namespace.MyClass} a
  84. */
  85. some.long.namespace.MyClass.staticHelper = function(a) {
  86. ...
  87. };
  88. myapp.main = function() {
  89. var MyClass = some.long.namespace.MyClass;
  90. var staticHelper = some.long.namespace.MyClass.staticHelper;
  91. staticHelper(new MyClass());
  92. };
  93. 不要为命名空间起本地别名。命名空间应该只能使用 `goog.scope <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#goog-scope>`_ 命名别名。
  94. ::
  95. myapp.main = function() {
  96. var namespace = some.long.namespace;
  97. namespace.MyClass.staticHelper(new namespace.MyClass());
  98. };
  99. 避免访问一个别名类型的属性,除非它是一个枚举。
  100. ::
  101. /** @enum {string} */
  102. some.long.namespace.Fruit = {
  103. APPLE: 'a',
  104. BANANA: 'b'
  105. };
  106. myapp.main = function() {
  107. var Fruit = some.long.namespace.Fruit;
  108. switch (fruit) {
  109. case Fruit.APPLE:
  110. ...
  111. case Fruit.BANANA:
  112. ...
  113. }
  114. };
  115. ::
  116. myapp.main = function() {
  117. var MyClass = some.long.namespace.MyClass;
  118. MyClass.staticHelper(null);
  119. };
  120. 永远不要在全局环境中创建别名。只在函数体内使用它们。
  121. 文件名
  122. ~~~~~~~~~
  123. 为了避免在大小写敏感的平台上引起混淆,文件名应该小写。文件名应该以 ``.js`` 结尾,并且应该不包含除了 ``-`` 或 ``_`` (相比较 ``_`` 更推荐 ``-`` )以外的其它标点。
  124. 自定义 toString() 方法
  125. ------------------------
  126. 必须确保无误,并且无其他副作用。
  127. 你可以通过自定义 ``toString()`` 方法来控制对象如何字符串化他们自己。这没问题,但是你必须确保你的方法执行无误,并且无其他副作用。如果你的方法没有达到这个要求,就会很容易产生严重的问题。比如,如果 ``toString()`` 方法调用一个方法产生一个断言,断言可能要输出对象的名称,就又需要调用 ``toString()`` 方法。
  128. 延时初始化
  129. --------------
  130. 可以使用。
  131. 并不总在变量声明的地方就进行变量初始化,所以延时初始化是可行的。
  132. 明确作用域
  133. --------------
  134. 时常。
  135. 经常使用明确的作用域加强可移植性和清晰度。例如,在作用域链中不要依赖 ``window`` 。你可能想在其他应用中使用你的函数,这时此 ``window`` 就非彼 ``window`` 了。
  136. 代码格式
  137. ----------
  138. 我们原则上遵循 `C++格式规范 <http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Formatting>`_ ,并且进行以下额外的说明。
  139. 大括号
  140. ~~~~~~~~
  141. 由于隐含分号的插入,无论大括号括起来的是什么,总是在同一行上开始你的大括号。例如:
  142. ::
  143. if (something) {
  144. // ...
  145. } else {
  146. // …
  147. }
  148. 数组和对象初始化表达式
  149. ~~~~~~~~~~~~~~~~~~~~~~~~~
  150. 当单行数组和对象初始化表达式可以在一行写开时,写成单行是允许的。
  151. ::
  152. var arr = [1, 2, 3]; //之后无空格[或之前]
  153. var obj = {a: 1, b: 2, c: 3}; //之后无空格[或之前]
  154. 多行数组和对象初始化表达式缩进两个空格,括号的处理就像块一样单独成行。
  155. ::
  156. //对象初始化表达式
  157. var inset = {
  158. top: 10,
  159. right: 20,
  160. bottom: 15,
  161. left: 12
  162. };
  163. //数组初始化表达式
  164. this.rows_ = [
  165. '"Slartibartfast" <fjordmaster@magrathea.com>',
  166. '"Zaphod Beeblebrox" <theprez@universe.gov>',
  167. '"Ford Prefect" <ford@theguide.com>',
  168. '"Arthur Dent" <has.no.tea@gmail.com>',
  169. '"Marvin the Paranoid Android" <marv@googlemail.com>',
  170. 'the.mice@magrathea.com'
  171. ];
  172. //在方法调用中使用
  173. goog.dom.createDom(goog.dom.TagName.DIV, {
  174. id: 'foo',
  175. className: 'some-css-class',
  176. style: 'display:none'
  177. }, 'Hello, world!');
  178. 长标识符或值在对齐的初始化列表中存在问题,所以初始化值不必对齐。例如:
  179. ::
  180. CORRECT_Object.prototype = {
  181. a: 0,
  182. b: 1,
  183. lengthyName: 2
  184. };
  185. 不要像这样:
  186. ::
  187. WRONG_Object.prototype = {
  188. a : 0,
  189. b : 1,
  190. lengthyName: 2
  191. };
  192. 函数参数
  193. ~~~~~~~~~
  194. 如果可能,应该在同一行上列出所有函数参数。如果这样做将超出每行80个字符的限制,参数必须以一种可读性较好的方式进行换行。为了节省空间,在每一行你可以尽可能的接近80个字符,或者把每一个参数单独放在一行以提高可读性。缩进可能是四个空格,或者和括号对齐。下面是最常见的参数换行形式:
  195. ::
  196. // 四个空格,每行包括80个字符。适用于非常长的函数名,
  197. // 重命名不需要重新缩进,占用空间小。
  198. goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(
  199. veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
  200. tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
  201. // ...
  202. };
  203. //四个空格,每行一个参数。适用于长函数名,
  204. // 允许重命名,并且强调每一个参数。
  205. goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(
  206. veryDescriptiveArgumentNumberOne,
  207. veryDescriptiveArgumentTwo,
  208. tableModelEventHandlerProxy,
  209. artichokeDescriptorAdapterIterator) {
  210. // ...
  211. };
  212. // 缩进和括号对齐,每行80字符。 看上去是分组的参数,
  213. // 占用空间小。
  214. function foo(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
  215. tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
  216. // ...
  217. }
  218. // 和括号对齐,每行一个参数。看上去是分组的并且
  219. // 强调每个单独的参数。
  220. function bar(veryDescriptiveArgumentNumberOne,
  221. veryDescriptiveArgumentTwo,
  222. tableModelEventHandlerProxy,
  223. artichokeDescriptorAdapterIterator) {
  224. // ...
  225. }
  226. 当函数调用本身缩进,你可以自由地开始相对于原始声明的开头或者相对于当前函数调用的开头,进行4个空格的缩进。以下都是可接受的缩进风格。
  227. ::
  228. if (veryLongFunctionNameA(
  229. veryLongArgumentName) ||
  230. veryLongFunctionNameB(
  231. veryLongArgumentName)) {
  232. veryLongFunctionNameC(veryLongFunctionNameD(
  233. veryLongFunctioNameE(
  234. veryLongFunctionNameF)));
  235. }
  236. 匿名函数传递
  237. ~~~~~~~~~~~~~~
  238. 当在一个函数的参数列表中声明一个匿名函数时,函数体应该与声明的左边缘缩进两个空格,或者与function关键字的左边缘缩进两个空格。这是为了匿名函数体更加可读(即不被挤在屏幕的右侧)。
  239. ::
  240. prefix.something.reallyLongFunctionName('whatever', function(a1, a2) {
  241. if (a1.equals(a2)) {
  242. someOtherLongFunctionName(a1);
  243. } else {
  244. andNowForSomethingCompletelyDifferent(a2.parrot);
  245. }
  246. });
  247. var names = prefix.something.myExcellentMapFunction(
  248. verboselyNamedCollectionOfItems,
  249. function(item) {
  250. return item.name;
  251. });
  252. 使用goog.scope命名别名
  253. ~~~~~~~~~~~~~~~~~~~~~~~
  254. `goog.scope <https://docs.google.com/document/d/1ETFAuh2kaXMVL-vafUYhaWlhl6b5D9TOvboVg7Zl68Y/pub>`_ 可用于在使用 `the Closure Library <https://developers.google.com/closure/library/?csw=1>`_ 的工程中缩短命名空间的符号引用。
  255. 每个文件只能添加一个 ``goog.scope`` 调用。始终将它放在全局范围内。
  256. 开放的 ``goog.scope(function() {`` 调用必须在之前有一个空行,并且紧跟 ``goog.provide`` 声明、 ``goog.require`` 声明或者顶层的注释。调用必须在文件的最后一行闭合。在scope声明闭合处追加 ``// goog.scope`` 。注释与分号间隔两个空格。
  257. 和C++命名空间相似,不要在 ``goog.scope`` 声明下面缩进。相反,从第0列开始。
  258. 只取不会重新分配给另一个对象(例如大多数的构造函数、枚举和命名空间)的别名。不要这样做:
  259. ::
  260. goog.scope(function() {
  261. var Button = goog.ui.Button;
  262. Button = function() { ... };
  263. ...
  264. 别名必须和全局中的命名的最后一个属性相同。
  265. ::
  266. goog.provide('my.module');
  267. goog.require('goog.dom');
  268. goog.require('goog.ui.Button');
  269. goog.scope(function() {
  270. var Button = goog.ui.Button;
  271. var dom = goog.dom;
  272. // Alias new types after the constructor declaration.
  273. my.module.SomeType = function() { ... };
  274. var SomeType = my.module.SomeType;
  275. // Declare methods on the prototype as usual:
  276. SomeType.prototype.findButton = function() {
  277. // Button as aliased above.
  278. this.button = new Button(dom.getElement('my-button'));
  279. };
  280. ...
  281. }); // goog.scope
  282. 更多的缩进
  283. ~~~~~~~~~~~~
  284. 事实上,除了 `初始化数组和对象 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Array_and_Object_literals>`_ 和传递匿名函数外,所有被拆开的多行文本应与之前的表达式左对齐,或者以4个(而不是2个)空格作为一缩进层次。
  285. ::
  286. someWonderfulHtml = '' +
  287. getEvenMoreHtml(someReallyInterestingValues, moreValues,
  288. evenMoreParams, 'a duck', true, 72,
  289. slightlyMoreMonkeys(0xfff)) +
  290. '';
  291. thisIsAVeryLongVariableName =
  292. hereIsAnEvenLongerOtherFunctionNameThatWillNotFitOnPrevLine();
  293. thisIsAVeryLongVariableName = 'expressionPartOne' + someMethodThatIsLong() +
  294. thisIsAnEvenLongerOtherFunctionNameThatCannotBeIndentedMore();
  295. someValue = this.foo(
  296. shortArg,
  297. 'Some really long string arg - this is a pretty common case, actually.',
  298. shorty2,
  299. this.bar());
  300. if (searchableCollection(allYourStuff).contains(theStuffYouWant) &&
  301. !ambientNotification.isActive() && (client.isAmbientSupported() ||
  302. client.alwaysTryAmbientAnyways())) {
  303. ambientNotification.activate();
  304. }
  305. 空行
  306. ~~~~~~
  307. 使用新的空行来划分一组逻辑上相关联的代码片段。例如:
  308. ::
  309. doSomethingTo(x);
  310. doSomethingElseTo(x);
  311. andThen(x);
  312. nowDoSomethingWith(y);
  313. andNowWith(z);
  314. 二元和三元操作符
  315. ~~~~~~~~~~~~~~~~~~~
  316. 操作符始终跟随着前行, 这样你就不用顾虑分号的隐式插入问题。否则换行符和缩进还是遵循其他谷歌规范指南。
  317. ::
  318. var x = a ? b : c; // All on one line if it will fit.
  319. // Indentation +4 is OK.
  320. var y = a ?
  321. longButSimpleOperandB : longButSimpleOperandC;
  322. // Indenting to the line position of the first operand is also OK.
  323. var z = a ?
  324. moreComplicatedB :
  325. moreComplicatedC;
  326. 点号也应如此处理。
  327. ::
  328. var x = foo.bar().
  329. doSomething().
  330. doSomethingElse();
  331. 括号
  332. ----------
  333. 只用在有需要的地方。
  334. 通常只在语法或者语义需要的地方有节制地使用。
  335. 绝对不要对一元运算符如 ``delete`` 、 ``typeof`` 和 ``void`` 使用括号或者在关键词如 ``return`` 、 ``throw`` 和其他的( ``case`` 、 ``in`` 或者 ``new`` )之后使用括号。
  336. 字符串
  337. --------
  338. 使用 ``'`` 代替 ``"`` 。
  339. 使用单引号( ``'`` )代替双引号( ``"`` )来保证一致性。当我们创建包含有HTML的字符串时这样做很有帮助。
  340. ::
  341. var msg = 'This is some HTML';
  342. 可见性(私有和保护类型字段)
  343. -----------------------------
  344. 鼓励使用 ``@private`` 和 ``@protected`` JSDoc注释。
  345. 我们建议使用JSDoc注释 ``@private`` 和 ``@protected`` 来标识出类、函数和属性的可见程度。
  346. 设置 ``--jscomp_warning=visibility`` 可令编译器对可见性的违规进行编译器警告。可见 `封闭的编译器警告 <https://code.google.com/p/closure-compiler/wiki/Warnings>`_ 。
  347. 加了 ``@private`` 标记的全局变量和函数只能被同一文件中的代码所访问。
  348. 被标记为 ``@private`` 的构造函数只能被同一文件中的代码或者它们的静态和实例成员实例化。 ``@private`` 标记的构造函数可以被相同文件内它们的公共静态属性和 ``instanceof`` 运算符访问。
  349. 全局变量、函数和构造函数不能注释 ``@protected`` 。
  350. ::
  351. // 文件1
  352. // AA_PrivateClass_ 和 AA_init_ 是全局的并且在同一个文件中所以能被访问
  353. /**
  354. * @private
  355. * @constructor
  356. */
  357. AA_PrivateClass_ = function() {
  358. };
  359. /** @private */
  360. function AA_init_() {
  361. return new AA_PrivateClass_();
  362. }
  363. AA_init_();
  364. 标记 ``@private`` 的属性可以被同一文件中的所有的代码访问,如果属性属于一个类,那么所有自身含有属性的类的静态方法和实例方法也可访问。它们不能被不同文件下的子类访问或者重写。
  365. 标记 ``@protected`` 的属性可以被同一文件中的所有的代码访问,任何含有属性的子类的静态方法和实例方法也可访问。
  366. 注意这些语义和C++、JAVA中private 和 protected的不同,其许可同一文件中的所有代码访问的权限,而不是仅仅局限于同一类或者同一类层次。此外,不像C++中,子类不可重写私有属性。
  367. ::
  368. // File 1.
  369. /** @constructor */
  370. AA_PublicClass = function() {
  371. /** @private */
  372. this.privateProp_ = 2;
  373. /** @protected */
  374. this.protectedProp = 4;
  375. };
  376. /** @private */
  377. AA_PublicClass.staticPrivateProp_ = 1;
  378. /** @protected */
  379. AA_PublicClass.staticProtectedProp = 31;
  380. /** @private */
  381. AA_PublicClass.prototype.privateMethod_ = function() {};
  382. /** @protected */
  383. AA_PublicClass.prototype.protectedMethod = function() {};
  384. // File 2.
  385. /**
  386. * @return {number} The number of ducks we've arranged in a row.
  387. */
  388. AA_PublicClass.prototype.method = function() {
  389. // Legal accesses of these two properties.
  390. return this.privateProp_ + AA_PublicClass.staticPrivateProp_;
  391. };
  392. // File 3.
  393. /**
  394. * @constructor
  395. * @extends {AA_PublicClass}
  396. */
  397. AA_SubClass = function() {
  398. // Legal access of a protected static property.
  399. AA_PublicClass.staticProtectedProp = this.method();
  400. };
  401. goog.inherits(AA_SubClass, AA_PublicClass);
  402. /**
  403. * @return {number} The number of ducks we've arranged in a row.
  404. */
  405. AA_SubClass.prototype.method = function() {
  406. // Legal access of a protected instance property.
  407. return this.protectedProp;
  408. };
  409. 注意在Javascript中,一个类(如 ``AA_PrivateClass_`` )和其构造函数类型是没有区别的。没办法确定一种类型是public而它的构造函数是private。(因为构造函数很容易重命名从而躲避隐私检查)。
  410. JavaScript类型
  411. -----------------
  412. 鼓励和强制执行的编译器。
  413. JSDoc记录类型时,要尽可能具体和准确。我们支持的类型是基于 `EcmaScript 4规范 <http://wiki.ecmascript.org/doku.php?id=spec:spec>`_ 。
  414. JavaScript类型语言
  415. ~~~~~~~~~~~~~~~~~~~
  416. ES4提案包含指定JavaScript类型的语言。我们使用JsDoc这种语言表达函数参数和返回值的类型。
  417. 随着ES4提议的发展,这种语言已经改变了。编译器仍然支持旧的语法类型,但这些语法已经被弃用了。
  418. .. list-table::
  419. :widths: 8 30 50 8
  420. :header-rows: 1
  421. * - 语法名称
  422. - 语法
  423. - 描述
  424. - 弃用语法
  425. * - 原始类型
  426. - 在JavaScript中有5种原始类型: ``{null}`` , ``{undefined}`` , ``{boolean}`` , ``{number}`` ,和 ``{string}``
  427. - 类型的名称。
  428. -
  429. * - 实例类型
  430. - ``{Object}``
  431. 实例对象或空。
  432. ``{Function}``
  433. 一个实例函数或空。
  434. ``{EventTarget}``
  435. 构造函数实现的EventTarget接口,或者为null的一个实例。
  436. - 一个实例构造函数或接口函数。构造函数是 ``@constructor`` JSDoc标记定义的函数 。接口函数是 ``@interface`` JSDoc标记定义的函数。
  437. 默认情况下,实例类型将接受空。这是唯一的类型语法,使得类型为空。此表中的其他类型的语法不会接受空。
  438. -
  439. * - 枚举类型
  440. - ``{goog.events.EventType}`` 字面量初始化对象的属性之一 ``goog.events.EventType`` 。
  441. - 一个枚举必须被初始化为一个字面量对象,或作为另一个枚举的别名,加注 ``@enum`` JSDoc标记。这个属性是枚举实例。 `下面 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#enums>`_ 是枚举语法的定义。
  442. 请注意,这是我们的类型系统中为数不多的ES4规范以外的事情之一。
  443. -
  444. * - 应用类型
  445. - ``{Array.<string>}`` 字符串数组。
  446. ``{Object.<string, number>}`` 一个对象,其中键是字符串,值是数字。
  447. - 参数化类型,该类型应用一组参数类型。这个想法是类似于Java泛型。
  448. -
  449. * - 联合类型
  450. - ``{(number|boolean)}`` 一个数字或布尔值。
  451. - 表明一个值可能有A型或B型。
  452. 括号在顶层表达式可以省略,但在子表达式不能省略,以避免歧义。
  453. ``{number|boolean}``
  454. ``{function(): (number|boolean)}``
  455. - ``{(number,boolean)}`` ,
  456. ``{(number||boolean)}``
  457. * - 可为空的类型
  458. - ``{?number}``
  459. 一个数字或空。
  460. - 空类型与任意其他类型组合的简称。这仅仅是语法糖(syntactic sugar)。
  461. - ``{number?}``
  462. * - 非空类型
  463. - ``{!Object}``
  464. 一个对象,值非空。
  465. - 从非空类型中过滤掉null。最常用于实例类型,默认可为空。
  466. - ``{Object!}``
  467. * - 记录类型
  468. - ``{{myNum: number, myObject}}``
  469. 给定成员类型的匿名类型。
  470. - 表示该值有指定的类型的成员。在这种情况下, ``myNum`` 是 ``number`` 类型而 ``myObject`` 可为任何类型。
  471. 注意花括号是语法类型的一部分。例如,表示一个数组对象有一个 ``length`` 属性,你可以写 ``Array.<{length}>`` 。
  472. -
  473. * - 函数类型
  474. - ``{function(string, boolean)}``
  475. 一个函数接受两个参数(一个字符串和一个布尔值),并拥有一个未知的返回值。
  476. - 指定一个函数。
  477. -
  478. * - 函数返回类型
  479. - ``{function(): number}``
  480. 一个函数没有参数并返回一个数字。
  481. - 指定函数的返回类型。
  482. -
  483. * - 函数 ``this`` 类型
  484. - ``{function(this:goog.ui.Menu, string)}``
  485. 一个需要一个参数(字符串)的函数,执行上下文是 ``goog.ui.Menu``
  486. - 指定函数类型的上下文类型。
  487. -
  488. * - 函数 ``new`` 类型
  489. - ``{function(new:goog.ui.Menu, string)}``
  490. 一个构造函数接受一个参数(一个字符串),并在使用“new”关键字时创建一个 ``goog.ui.Menu`` 新实例。
  491. - 指定构造函数所构造的类型。
  492. -
  493. * - 可变参数
  494. - ``{function(string, ...[number]): number}``
  495. 一个函数,它接受一个参数(一个字符串),然后一个可变数目的参数,必须是数字。
  496. - 指定函数的变量参数。
  497. -
  498. * - 可变参数( ``@param`` 注释)
  499. - ``@param {...number} var_args``
  500. 带注释函数的可变数目参数。
  501. - 指定带注释函数接受一个可变数目的参数。
  502. -
  503. * - 函数 `可选参数 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#optional>`_
  504. - ``{function(?string=, number=)}``
  505. 一个函数,它接受一个可选的、可以为空的字符串和一个可选的数字作为参数。“=”只用于函数类型声明。
  506. - 指定函数的可选参数。
  507. -
  508. * - 函数 `可选参数 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#optional>`_ ( ``@param`` 注释)
  509. - ``@param {number=} opt_argument``
  510. ``number`` 类型的可选参数。
  511. - 指定带注释函数接受一个可选的参数。
  512. -
  513. * - 所有类型
  514. - ``{*}``
  515. - 表明该变量可以接受任何类型。
  516. -
  517. * - 未知类型
  518. - ``{?}``
  519. - 表明该变量可以接受任何类型,编译器不应该检查其类型。
  520. -
  521. JavaScript中的类型
  522. ~~~~~~~~~~~~~~~~~~~
  523. .. list-table::
  524. :widths: 20 30 50
  525. :header-rows: 1
  526. * - 类型举例
  527. - 取值举例
  528. - 描述
  529. * - number
  530. - ::
  531. 1
  532. 1.0
  533. -5
  534. 1e5
  535. Math.PI
  536. -
  537. * - Number
  538. - ::
  539. new Number(true)
  540. - `Number对象 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Wrapper_objects_for_primitive_types>`_
  541. * - string
  542. - ::
  543. 'Hello'
  544. "World"
  545. String(42)
  546. - 字符串
  547. * - String
  548. - ::
  549. new String('Hello')
  550. new String(42)
  551. - `String对象 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Wrapper_objects_for_primitive_types>`_
  552. * - boolean
  553. - ::
  554. true
  555. false
  556. Boolean(0)
  557. - Boolean值
  558. * - Boolean
  559. - ::
  560. new Boolean(true)
  561. - `Boolean对象 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Wrapper_objects_for_primitive_types>`_
  562. * - RegExp
  563. - ::
  564. new RegExp('hello')
  565. /world/g
  566. -
  567. * - Date
  568. - ::
  569. new Date
  570. new Date()
  571. -
  572. * - null
  573. - ::
  574. null
  575. -
  576. * - undefined
  577. - ::
  578. undefined
  579. -
  580. * - void
  581. - ::
  582. function f() {
  583. return;
  584. }
  585. - 没有返回值
  586. * - Array
  587. - ::
  588. ['foo', 0.3, null]
  589. []
  590. - 无类型数组
  591. * - Array.<number>
  592. - ::
  593. [11, 22, 33]
  594. - 数字数组
  595. * - Array.<Array.<string>>
  596. - ::
  597. [['one', 'two', 'three'], ['foo', 'bar']]
  598. - 以字符串为元素的数组,作为另一个数组的元素
  599. * - Object
  600. - ::
  601. {}
  602. {foo: 'abc', bar: 123, baz: null}
  603. -
  604. * - Object.<string>
  605. - ::
  606. {'foo': 'bar'}
  607. - 值为字符串的对象
  608. * - Object.<number, string>
  609. - ::
  610. var obj = {};
  611. obj[1] = 'bar';
  612. - 键为整数,值为字符串的对象。
  613. 注意,js当中键总是会隐式转换为字符串。所以 ``obj['1'] == obj[1]`` 。键在for…in…循环中,总是字符串类型。但在对象中索引时编译器会验证键的类型。
  614. * - Function
  615. - ::
  616. function(x, y) {
  617. return x * y;
  618. }
  619. - `Function对象 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Wrapper_objects_for_primitive_types>`_
  620. * - function(number, number): number
  621. - ::
  622. function(x, y) {
  623. return x * y;
  624. }
  625. - 函数值
  626. * - 类
  627. - ::
  628. /** @constructor */
  629. function SomeClass() {}
  630. new SomeClass();
  631. -
  632. * - 接口
  633. - ::
  634. /** @interface */
  635. function SomeInterface() {}
  636. SomeInterface.prototype.draw = function() {};
  637. -
  638. * - project.MyClass
  639. - ::
  640. /** @constructor */
  641. project.MyClass = function () {}
  642. new project.MyClass()
  643. -
  644. * - project.MyEnum
  645. - ::
  646. /** @enum {string} */
  647. project.MyEnum = {
  648. /** The color blue. */
  649. BLUE: '#0000dd',
  650. /** The color red. */
  651. RED: '#dd0000'
  652. };
  653. - 枚举
  654. JSDoc中枚举的值都是可选的.
  655. * - Element
  656. - ::
  657. document.createElement('div')
  658. - DOM元素
  659. * - Node
  660. - ::
  661. document.body.firstChild
  662. - DOM节点
  663. * - HTMLInputElement
  664. - ::
  665. htmlDocument.getElementsByTagName('input')[0]
  666. - 指明类型的DOM元素
  667. 类型转换
  668. ~~~~~~~~~~
  669. 在类型检测不准确的情况下,有可能需要添加类型的注释,并且把类型转换的表达式写在括号里,括号是必须的。如:
  670. ::
  671. /** @type {number} */ (x)
  672. 可为空与可选的参数和属性
  673. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  674. 因为Javascript是一个弱类型的语言,明白函数参数、类属性的可选、可为空和未定义之间的细微差别是非常重要的。
  675. 对象类型和引用类型默认可为空。如以下表达式:
  676. ::
  677. /**
  678. * 传入值初始化的类
  679. * @param {Object} value某个值
  680. * @constructor
  681. */
  682. function MyClass(value) {
  683. /**
  684. * Some value.
  685. * @type {Object}
  686. * @private
  687. */
  688. this.myValue_ = value;
  689. }
  690. 告诉编译器 ``myValue_`` 属性为一对象或null。如果 ``myValue_`` 永远都不会为null, 就应该如下声明:
  691. ::
  692. /**
  693. * 传入非null值初始化的类
  694. * @param {!Object} value某个值
  695. * @constructor
  696. */
  697. function MyClass(value) {
  698. /**
  699. * Some value.
  700. * @type {!Object}
  701. * @private
  702. */
  703. this.myValue_ = value;
  704. }
  705. 这样,如果编译器可以识别出 ``MyClass`` 初始化传入值为null,就会发出一个警告。
  706. 函数的可选参数在运行时可能会是undefined,所以如果他们是类的属性,那么必须声明:
  707. ::
  708. /**
  709. * 传入可选值初始化的类
  710. * @param {Object=} opt_value某个值(可选)
  711. * @constructor
  712. */
  713. function MyClass(opt_value) {
  714. /**
  715. * Some value.
  716. * @type {Object|undefined}
  717. * @private
  718. */
  719. this.myValue_ = opt_value;
  720. }
  721. 这告诉编译器 ``myValue_`` 可能是一个对象,或 ``null`` ,或 ``undefined`` 。
  722. 注意: 可选参数 ``opt_value`` 被声明成 ``{Object=}`` ,而不是 ``{Object|undefined}`` 。这是因为可选参数可能是undefined。虽然直接写undefined也并无害处,但鉴于可阅读性还是写成上述的样子。
  723. 最后,属性的可为空和可选并不矛盾,下面的四种声明各不相同:
  724. ::
  725. /**
  726. * 接受四个参数,两个可为空,两个可选
  727. * @param {!Object} nonNull 必不为null
  728. * @param {Object} mayBeNull 可为null
  729. * @param {!Object=} opt_nonNull 可选但必不为null
  730. * @param {Object=} opt_mayBeNull 可选可为null
  731. */
  732. function strangeButTrue(nonNull, mayBeNull, opt_nonNull, opt_mayBeNull) {
  733. // ...
  734. };
  735. 类型定义
  736. ~~~~~~~~~~
  737. 有时类型可以变得复杂。一个函数,它接受一个元素的内容可能看起来像:
  738. ::
  739. /**
  740. * @param {string} tagName
  741. * @param {(string|Element|Text|Array.<Element>|Array.<Text>)} contents
  742. * @return {!Element}
  743. */
  744. goog.createElement = function(tagName, contents) {
  745. ...
  746. };
  747. 你可以定义带 ``@typedef`` 标记的常用类型表达式。例如:
  748. ::
  749. /** @typedef {(string|Element|Text|Array.<Element>|Array.<Text>)} */
  750. goog.ElementContent;
  751. /**
  752. * @param {string} tagName
  753. * @param {goog.ElementContent} contents
  754. * @return {!Element}
  755. */
  756. goog.createElement = function(tagName, contents) {
  757. ...
  758. };
  759. 模板类型
  760. ~~~~~~~~~~
  761. 编译器对模板类型提供有限支持。它只能从字面上通过 ``this`` 参数的类型和 ``this`` 参数是否丢失推断匿名函数的 ``this`` 类型。
  762. ::
  763. /**
  764. * @param {function(this:T, ...)} fn
  765. * @param {T} thisObj
  766. * @param {...*} var_args
  767. * @template T
  768. */
  769. goog.bind = function(fn, thisObj, var_args) {
  770. ...
  771. };
  772. //可能出现属性丢失警告
  773. goog.bind(function() { this.someProperty; }, new SomeClass());
  774. //出现this未定义警告
  775. goog.bind(function() { this.someProperty; });
  776. .. _js-comments:
  777. 注释
  778. ----------
  779. 使用JSDoc。
  780. 我们使用 `c++的注释风格 <http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Comments>`_ 。
  781. 所有的文件、类、方法和属性都应该用合适的 `JSDoc <https://code.google.com/p/jsdoc-toolkit/>`_ 的 `标签 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#JSDoc_Tag_Reference>`_ 和 `类型 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#JsTypes>`_ 注释。除了直观的方法名称和参数名称外,方法的描述、方法的参数以及方法的返回值也要包含进去。
  782. 行内注释应该使用 ``//`` 的形式。
  783. 为了避免出现语句片段,要使用正确的大写单词开头,并使用正确的标点符号作为结束。
  784. 注释语法
  785. ~~~~~~~~~~
  786. JSDoc的语法基于 `JavaDoc <http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html>`_ ,许多编译工具从JSDoc注释中获取信息从而进行代码验证和优化,所以这些注释必须符合语法规则。
  787. ::
  788. /**
  789. * A JSDoc comment should begin with a slash and 2 asterisks.
  790. * Inline tags should be enclosed in braces like {@code this}.
  791. * @desc Block tags should always start on their own line.
  792. */
  793. JSDoc 缩进
  794. ~~~~~~~~~~~~~
  795. 如果你不得不进行换行,那么你应该像在代码里那样,使用四个空格进行缩进。
  796. ::
  797. /**
  798. * Illustrates line wrapping for long param/return descriptions.
  799. * @param {string} foo This is a param with a description too long to fit in
  800. * one line.
  801. * @return {number} This returns something that has a description too long to
  802. * fit in one line.
  803. */
  804. project.MyClass.prototype.method = function(foo) {
  805. return 5;
  806. };
  807. 不必在 ``@fileoverview`` 标记中使用缩进。
  808. 虽然不建议,但依然可以对描述文字进行排版。
  809. ::
  810. /**
  811. * This is NOT the preferred indentation method.
  812. * @param {string} foo This is a param with a description too long to fit in
  813. * one line.
  814. * @return {number} This returns something that has a description too long to
  815. * fit in one line.
  816. */
  817. project.MyClass.prototype.method = function(foo) {
  818. return 5;
  819. };
  820. JSDoc中的HTML
  821. ~~~~~~~~~~~~~~~~
  822. 像JavaDoc一样, JSDoc 支持很多的HTML标签,像 ``<code>`` , ``<pre>`` , ``<tt>`` , ``<strong>`` , ``<ul>`` , ``<ol>`` , ``<li>`` , ``<a>`` 等。
  823. 这就意味着不建议采用纯文本的格式。所以,不要在JSDoc里使用空白符进行格式化。
  824. ::
  825. /**
  826. * Computes weight based on three factors:
  827. * items sent
  828. * items received
  829. * last timestamp
  830. */
  831. 上面的注释会变成这样:
  832. ::
  833. Computes weight based on three factors: items sent items received items received last timestamp
  834. 所以,用下面的方式代替:
  835. ::
  836. /**
  837. * Computes weight based on three factors:
  838. * <ul>
  839. * <li>items sent
  840. * <li>items received
  841. * <li>last timestamp
  842. * </ul>
  843. */
  844. `JavaDoc <http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html>`_ 风格指南对于如何编写良好的doc注释是非常有帮助的。
  845. 顶层/文件层注释
  846. ~~~~~~~~~~~~~~~~~~
  847. `版权声明 <http://google-styleguide.googlecode.com/svn/trunk/copyright.html>`_ 和作者信息是可选的。顶层注释的目的是为了让不熟悉代码的读者了解文件中有什么。它需要描述文件内容,依赖关系以及兼容性的信息。例如:
  848. ::
  849. /**
  850. * @fileoverview Description of file, its uses and information
  851. * about its dependencies.
  852. */
  853. Class评论
  854. ~~~~~~~~~~~
  855. 类必须记录说明与描述和 `一个类型的标签 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#constructor-tag>`_ ,标识的构造函数。类必须加以描述,若是构造函数则需标注出。
  856. ::
  857. /**
  858. * Class making something fun and easy.
  859. * @param {string} arg1 An argument that makes this more interesting.
  860. * @param {Array.<number>} arg2 List of numbers to be processed.
  861. * @constructor
  862. * @extends {goog.Disposable}
  863. */
  864. project.MyClass = function(arg1, arg2) {
  865. // ...
  866. };
  867. goog.inherits(project.MyClass, goog.Disposable);
  868. 方法和功能注释
  869. ~~~~~~~~~~~~~~~
  870. 参数和返回类型应该被记录下来。如果方法描述从参数或返回类型的描述中明确可知则可以省略。方法描述应该由一个第三人称表达的句子开始。
  871. ::
  872. /**
  873. * Operates on an instance of MyClass and returns something.
  874. * @param {project.MyClass} obj Instance of MyClass which leads to a long
  875. * comment that needs to be wrapped to two lines.
  876. * @return {boolean} Whether something occured.
  877. */
  878. function PR_someMethod(obj) {
  879. // ...
  880. }
  881. 属性评论
  882. ~~~~~~~~~~
  883. ::
  884. /** @constructor */
  885. project.MyClass = function() {
  886. /**
  887. * Maximum number of things per pane.
  888. * @type {number}
  889. */
  890. this.someProperty = 4;
  891. }
  892. JSDoc标签参考
  893. ~~~~~~~~~~~~~~~
  894. .. list-table::
  895. :widths: 20 30 50
  896. :header-rows: 1
  897. * - 标签
  898. - 模板及实例
  899. - 描述
  900. * - @author
  901. - @author username@google.com (first last)
  902. 例如:
  903. ::
  904. /**
  905. * @fileoverview Utilities for handling textareas.
  906. * @author kuth@google.com (Uthur Pendragon)
  907. */
  908. - 说明文件的作者是谁,一般只会在 ``@fileoverview`` 里用到。
  909. * - @code
  910. - {@code ...}
  911. 例如:
  912. ::
  913. /**
  914. * Moves to the next position in the selection.
  915. * Throws {@code goog.iter.StopIteration} when it
  916. * passes the end of the range.
  917. * @return {Node} The node at the next position.
  918. */
  919. goog.dom.RangeIterator.prototype.next = function() {
  920. // ...
  921. };
  922. - 表示这是一段代码,他能在文档中正确的格式化。
  923. * - @const
  924. - @const
  925. @const {type}
  926. 例如:
  927. ::
  928. /** @const \*/ var MY_BEER = 'stout';
  929. /**
  930. * My namespace's favorite kind of beer.
  931. * @const {string}
  932. */
  933. mynamespace.MY_BEER = 'stout';
  934. /** @const \*/ MyClass.MY_BEER = 'stout';
  935. /**
  936. * Initializes the request.
  937. * @const
  938. */
  939. mynamespace.Request.prototype.initialize = function() {
  940. // This method cannot be overriden in a subclass.
  941. }
  942. - 说明变量或者属性是只读的,适合内联。
  943. 标记为 ``@const`` 的变量是不可变的。如果变量或属性试图覆盖他的值,那么js编译器会给出警告。
  944. 如果某一个值可以清楚地分辨出是不是常量,可以省略类型声明。变量附加的注释是可选的。
  945. 当一个方法被标记为 ``@const`` ,意味着这个方法不仅不可以被覆盖,而且也不能在子类中重写。
  946. ``@const`` 的更多信息,请看 `常量 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Constants>`_ 部分
  947. * - @constructor
  948. - @constructor
  949. 例如:
  950. ::
  951. /**
  952. * A rectangle.
  953. * @constructor
  954. */
  955. function GM_Rect() {
  956. ...
  957. }
  958. - 在一个类的文档中表示构造函数。
  959. * - @define
  960. - @define {Type} description
  961. 例如:
  962. ::
  963. /** @define {boolean} */
  964. var TR_FLAGS_ENABLE_DEBUG = true;
  965. /** @define {boolean} */
  966. goog.userAgent.ASSUME_IE = false;
  967. - 指明一个在编译时可以被覆盖的常量。
  968. 在这个例子中,编译器标志 ``--define='goog.userAgent.ASSUME_IE=true'`` 表明在构建文件的时侯变量 ``goog.userAgent.ASSUME_IE`` 可以被赋值为 ``true`` 。
  969. * - @deprecated
  970. - @deprecated Description
  971. 例如:
  972. ::
  973. /**
  974. * Determines whether a node is a field.
  975. * @return {boolean} True if the contents of
  976. * the element are editable, but the element
  977. * itself is not.
  978. * @deprecated Use isField().
  979. */
  980. BN_EditUtil.isTopEditableField = function(node) {
  981. // ...
  982. };
  983. - 说明函数、方法或者属性已经不可用,常说明替代方法或者属性。
  984. * - @dict
  985. - @dict Description
  986. 例如:
  987. ::
  988. /**
  989. * @constructor
  990. * @dict
  991. */
  992. function Foo(x) {
  993. this['x'] = x;
  994. }
  995. var obj = new Foo(123);
  996. var num = obj.x; // warning
  997. (/** @dict \*/ { x: 1 }).x = 123; // warning
  998. - 当构造函数 (例子里的Foo)被标记为 ``@dict`` ,你只能使用括号表示法访问 ``Foo`` 的属性。这个注释也可以直接使用对象表达式。
  999. * - @enum
  1000. - @enum {Type}
  1001. 例如:
  1002. ::
  1003. /**
  1004. * Enum for tri-state values.
  1005. * @enum {number}
  1006. */
  1007. project.TriState = {
  1008. TRUE: 1,
  1009. FALSE: -1,
  1010. MAYBE: 0
  1011. };
  1012. -
  1013. * - @export
  1014. - @export
  1015. 例如:
  1016. ::
  1017. /** @export */
  1018. foo.MyPublicClass.prototype.myPublicMethod = function() {
  1019. // ...
  1020. };
  1021. - 对于例子中的代码,当编译到 ``--generate_exports`` 标记时,将会产生以下代码:
  1022. ::
  1023. goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod',
  1024. foo.MyPublicClass.prototype.myPublicMethod);
  1025. 也就是输出了没有编译的代码。使用@export标签时,应该:
  1026. 1. 包含 ``//javascript/closure/base.js`` , 或者
  1027. 2. 同时定义 ``goog.exportSymbol`` 和 ``goog.exportProperty`` 并且要使用相同的调用方法。
  1028. * - @expose
  1029. - @expose
  1030. 例如:
  1031. ::
  1032. /** @expose */
  1033. MyClass.prototype.exposedProperty = 3;
  1034. - 声明一个公开的属性,表示这个属性不可以被删除、重命名或者由编译器进行优化。相同名称的属性也不能由编译器通过任何方式进行优化。
  1035. ``@expose`` 不可以出现在代码库里,因为他会阻止这个属性被删除。
  1036. * - @extends
  1037. - @extends Type
  1038. @extends {Type}
  1039. 例如:
  1040. ::
  1041. /**
  1042. * Immutable empty node list.
  1043. * @constructor
  1044. * @extends goog.ds.BasicNodeList
  1045. */
  1046. goog.ds.EmptyNodeList = function() {
  1047. ...
  1048. };
  1049. - 和 ``@constructor`` 一起使用,表示从哪里继承过来的。类型外的大括号是可选的。
  1050. * - @externs
  1051. - @externs
  1052. 例如:
  1053. ::
  1054. /**
  1055. * @fileoverview This is an externs file.
  1056. * @externs
  1057. */
  1058. var document;
  1059. - 声明一个外部文件。
  1060. * - @fileoverview
  1061. - @fileoverview Description
  1062. 例如:
  1063. ::
  1064. /**
  1065. * @fileoverview Utilities for doing things that require this very long
  1066. * but not indented comment.
  1067. * @author kuth@google.com (Uthur Pendragon)
  1068. */
  1069. - 使注释提供文件级别的信息。
  1070. * - @implements
  1071. - @implements Type
  1072. @implements {Type}
  1073. 例如:
  1074. ::
  1075. /**
  1076. * A shape.
  1077. * @interface
  1078. */
  1079. function Shape() {};
  1080. Shape.prototype.draw = function() {};
  1081. /**
  1082. * @constructor
  1083. * @implements {Shape}
  1084. */
  1085. function Square() {};
  1086. Square.prototype.draw = function() {
  1087. ...
  1088. };
  1089. - 使用 ``@constructor`` 来表示一个类实现了某个接口。类型外的大括号是可选的。
  1090. * - @inheritDoc
  1091. - @inheritDoc
  1092. 例如:
  1093. ::
  1094. /** @inheritDoc */
  1095. project.SubClass.prototype.toString() {
  1096. // ...
  1097. };
  1098. - **已废弃。使用@override代替**
  1099. 表示一个子类中的方法或者属性覆盖父类的方法或者属性,并且拥有相同的文档。注意, ``@inheritDoc`` 等同 ``@override``
  1100. * - @interface
  1101. - @interface
  1102. 例如:
  1103. ::
  1104. /**
  1105. * A shape.
  1106. * @interface
  1107. */
  1108. function Shape() {};
  1109. Shape.prototype.draw = function() {};
  1110. /**
  1111. * A polygon.
  1112. * @interface
  1113. * @extends {Shape}
  1114. */
  1115. function Polygon() {};
  1116. Polygon.prototype.getSides = function() {};
  1117. - 表示一个函数定义了一个接口。
  1118. * - @lends
  1119. - @lends objectName
  1120. @lends {objectName}
  1121. 例如:
  1122. ::
  1123. goog.object.extend(
  1124. Button.prototype,
  1125. /** @lends {Button.prototype} */ {
  1126. isButton: function() { return true; }
  1127. });
  1128. - 表示对象的键是另外一个对象的属性。这个标记只能出现在对象字面量中。
  1129. 注意,括号中的名称和其他标记中的类型名称不一样,它是一个对象名,表明是从哪个对象“借过来”的属性。例如, ``@type {Foo}`` 意味着Foo的一个实例,但是 ``@lends {Foo}`` 意味着“Foo构造函数”.
  1130. `JSDoc Toolkit docs <https://code.google.com/p/jsdoc-toolkit/wiki/TagLends>`_ 中有关于更多此标记的信息。
  1131. * - @license or @preserve
  1132. - @license Description
  1133. 例如:
  1134. ::
  1135. /**
  1136. * @preserve Copyright 2009 SomeThirdParty.
  1137. * Here is the full license text and copyright
  1138. * notice for this file. Note that the notice can span several
  1139. * lines and is only terminated by the closing star and slash:
  1140. */
  1141. - 由 ``@licenseor`` 或 ``@preserve`` 标记的内容,会被编译器保留并放到文件的顶部。
  1142. 这个标记会让被标记的重要内容(例如法律许可或版权文本)原样输出,换行也是。
  1143. * - @noalias
  1144. - @noalias
  1145. 例如:
  1146. ::
  1147. /** @noalias */
  1148. function Range() {}
  1149. - 用在外部文件当中,告诉编译器,这里的变量或者方法不可以重命名。
  1150. * - @nosideeffects
  1151. - @nosideeffects
  1152. 例如:
  1153. ::
  1154. /** @nosideeffects */
  1155. function noSideEffectsFn1() {
  1156. // ...
  1157. };
  1158. /** @nosideeffects */
  1159. var noSideEffectsFn2 = function() {
  1160. // ...
  1161. };
  1162. /** @nosideeffects */
  1163. a.prototype.noSideEffectsFn3 = function() {
  1164. // ...
  1165. };
  1166. - 用于函数和构造函数,说明调用这个函数没有副作用。如果返回值未被使用,此注释允许编译器移除对该函数的调用。
  1167. * - @override
  1168. - @override
  1169. 例如:
  1170. ::
  1171. /**
  1172. * @return {string} Human-readable representation of project.SubClass.
  1173. * @override
  1174. */
  1175. project.SubClass.prototype.toString() {
  1176. // ...
  1177. };
  1178. - 表示子类的方法或者属性故意隐藏了父类的方法或属性。如果子类没有其他的文档,方法或属性也会从父类那里继承文档。
  1179. * - @param
  1180. - @param {Type} varname Description
  1181. 例如:
  1182. ::
  1183. /**
  1184. * Queries a Baz for items.
  1185. * @param {number} groupNum Subgroup id to query.
  1186. * @param {string|number|null} term An itemName,
  1187. * or itemId, or null to search everything.
  1188. */
  1189. goog.Baz.prototype.query = function(groupNum, term) {
  1190. // ...
  1191. };
  1192. - 给方法、函数、构造函数的参数添加文档说明。
  1193. `参数类型 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#JsTypes>`_ 一定要写在大括号里。如果类型被省略,编译器将不做类型检测。
  1194. * - @private
  1195. - @private
  1196. @private {type}
  1197. 例如:
  1198. ::
  1199. /**
  1200. * Handlers that are listening to this logger.
  1201. * @private {!Array.<Function>}
  1202. */
  1203. this.handlers\_ = [];
  1204. - 与方法或属性名结尾使用一个下划线来联合表明该成员是 `私有的 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Visibility__private_and_protected_fields_>`_ 。随着工具对 ``@private`` 的认可,结尾的下划线可能最终被废弃。
  1205. * - @protected
  1206. - @protected
  1207. @protected {type}
  1208. 例如:
  1209. ::
  1210. /**
  1211. * Sets the component's root element to the given element. Considered
  1212. * protected and final.
  1213. * @param {Element} element Root element for the component.
  1214. * @protected
  1215. */
  1216. goog.ui.Component.prototype.setElementInternal = function(element) {
  1217. // ...
  1218. };
  1219. - 用来表明成员或属性是 ``受保护的 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Visibility__private_and_protected_fields_>``_ 。成员或属性应使用没有跟随下划线的名称。
  1220. * - @return
  1221. - @return {Type} Description
  1222. 例如:
  1223. ::
  1224. /**
  1225. * @return {string} The hex ID of the last item.
  1226. */
  1227. goog.Baz.prototype.getLastId = function() {
  1228. // ...
  1229. return id;
  1230. };
  1231. - 在方法或函数调用时使用,来说明返回类型。给布尔值写注释时,写成类似“这个组件是否可见”比“如果组件可见则为true,否则为false”要好。如果没有返回值,不使用 ``@return`` 标签。
  1232. `类型 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#JsTypes>`_ 名称必须包含在大括号内。如果省略类型,编译器将不会检查返回值的类型。
  1233. * - @see
  1234. - @see Link
  1235. 例如:
  1236. ::
  1237. /**
  1238. * Adds a single item, recklessly.
  1239. * @see #addSafely
  1240. * @see goog.Collect
  1241. * @see goog.RecklessAdder#add
  1242. ...
  1243. - 参考查找另一个类或方法。
  1244. * - @struct
  1245. - @struct Description
  1246. 例如:
  1247. ::
  1248. /**
  1249. * @constructor
  1250. * @struct
  1251. */
  1252. function Foo(x) {
  1253. this.x = x;
  1254. }
  1255. var obj = new Foo(123);
  1256. var num = obj['x']; // warning
  1257. obj.y = "asdf"; // warning
  1258. Foo.prototype = /** @struct */ {
  1259. method1: function() {}
  1260. };
  1261. Foo.prototype.method2 = function() {}; // warning
  1262. - 当一个构造函数(在本例中 ``Foo`` )注释为 ``@struct`` ,你只能用点符号访问Foo对象的属性。此外,Foo对象创建后不能加新的属性。此注释也可以直接使用于对象字面量。
  1263. * - @supported
  1264. - @supported Description
  1265. 例如:
  1266. ::
  1267. /**
  1268. * @fileoverview Event Manager
  1269. * Provides an abstracted interface to the
  1270. * browsers' event systems.
  1271. * @supported So far tested in IE6 and FF1.5
  1272. */
  1273. - 用于在文件信息中说明该文档被哪些浏览器支持
  1274. * - @suppress
  1275. - @suppress {warning1|warning2}
  1276. 例如:
  1277. ::
  1278. /**
  1279. * @suppress {deprecated}
  1280. */
  1281. function f() {
  1282. deprecatedVersionOfF();
  1283. }
  1284. - 标明禁止工具发出的警告。警告类别用|分隔。
  1285. * - @template
  1286. - @template
  1287. 例如:
  1288. ::
  1289. /**
  1290. * @param {function(this:T, ...)} fn
  1291. * @param {T} thisObj
  1292. * @param {...*} var_args
  1293. * @template T
  1294. */
  1295. goog.bind = function(fn, thisObj, var_args) {
  1296. ...
  1297. };
  1298. - 这个注释可以用来声明一个 `模板类型名 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Template_types>`_ 。
  1299. * - @this
  1300. - @this Type
  1301. @this {Type}
  1302. 例如:
  1303. ::
  1304. pinto.chat.RosterWidget.extern('getRosterElement',
  1305. /**
  1306. * Returns the roster widget element.
  1307. * @this pinto.chat.RosterWidget
  1308. * @return {Element}
  1309. */
  1310. function() {
  1311. return this.getWrappedComponent_().getElement();
  1312. });
  1313. - 标明一个特定方法在其上下文中被调用的对象类型。用于 ``this`` 关键字是从一个非原型方法中使用时
  1314. * - @type
  1315. - @type Type
  1316. @type {Type}
  1317. 例如:
  1318. ::
  1319. /**
  1320. * The message hex ID.
  1321. * @type {string}
  1322. */
  1323. var hexId = hexId;
  1324. - 标识变量,属性或表达式的 `类型 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#JsTypes>`_ 。大多数类型不需要大括号,但有些项目为了保持一致性而要求所有类型都使用大括号。
  1325. * - @typedef
  1326. - @typedef
  1327. 例如:
  1328. ::
  1329. /** @typedef {(string|number)} */
  1330. goog.NumberLike;
  1331. /** @param {goog.NumberLike} x A number or a string. */
  1332. goog.readNumber = function(x) {
  1333. ...
  1334. }
  1335. - 使用此注释来声明一个更 `复杂的类型 <http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Typedefs>`_ 的别名。
  1336. 你也许在第三方代码中看到其他类型JSDoc注释,这些注释出现在 `JSDoc Toolkit标签的参考 <https://code.google.com/p/jsdoc-toolkit/wiki/TagReference>`_ ,但目前在谷歌的代码中不鼓励使用。你应该将他们当作“保留”字,他们包括:
  1337. * @augments
  1338. * @argument
  1339. * @borrows
  1340. * @class
  1341. * @constant
  1342. * @constructs
  1343. * @default
  1344. * @event
  1345. * @example
  1346. * @field
  1347. * @function
  1348. * @ignore
  1349. * @inner
  1350. * @link
  1351. * @memberOf
  1352. * @name
  1353. * @namespace
  1354. * @property
  1355. * @public
  1356. * @requires
  1357. * @returns
  1358. * @since
  1359. * @static
  1360. * @version
  1361. 为goog.provide提供依赖
  1362. --------------------------
  1363. 只提供顶级符号。
  1364. 一个类上定义的所有成员应该放在一个文件中。所以,在一个在相同类中定义的包含多个成员的文件中只应该提供顶级的类(例如枚举、内部类等)。
  1365. 要这样写:
  1366. ::
  1367. goog.provide('namespace.MyClass');
  1368. 不要这样写:
  1369. ::
  1370. goog.provide('namespace.MyClass');
  1371. goog.provide('namespace.MyClass.Enum');
  1372. goog.provide('namespace.MyClass.InnerClass');
  1373. goog.provide('namespace.MyClass.TypeDef');
  1374. goog.provide('namespace.MyClass.CONSTANT');
  1375. goog.provide('namespace.MyClass.staticMethod');
  1376. 命名空间的成员也应该提供:
  1377. ::
  1378. goog.provide('foo.bar');
  1379. goog.provide('foo.bar.method');
  1380. goog.provide('foo.bar.CONSTANT');
  1381. 编译
  1382. ------
  1383. 必需。
  1384. 对于所有面向客户的代码来说,使用JS编辑器是必需的,如使用 `Closure Compiler <https://developers.google.com/closure/compiler/?csw=1>`_ 。
  1385. 技巧和诀窍
  1386. --------------
  1387. JavaScript帮助信息
  1388. True和False布尔表达式
  1389. ~~~~~~~~~~~~~~~~~~~~~~~~~
  1390. 下边的布尔表达式都返回false:
  1391. * null
  1392. * undefined
  1393. * ''空字符串
  1394. * 数字0
  1395. 但是要小心,因为以下这些返回true:
  1396. * 字符串"0"
  1397. * []空数组
  1398. * {}空对象
  1399. 下面这样写不好:
  1400. ::
  1401. while (x != null) {
  1402. 你可以写成这种更短的代码(只要你不期望x为0、空字符串或者false):
  1403. ::
  1404. while (x) {
  1405. 如果你想检查字符串是否为null或空,你可以这样写:
  1406. ::
  1407. if (y != null && y != '') {
  1408. 但是以下这样会更简练更好:
  1409. ::
  1410. if (y) {
  1411. 注意:还有很多不直观的关于布尔表达式的例子,这里是一些:
  1412. * Boolean('0') == true
  1413. '0' != true
  1414. * 0 != null
  1415. 0 == []
  1416. 0 == false
  1417. * Boolean(null) == false
  1418. null != true
  1419. null != false
  1420. * Boolean(undefined) == false
  1421. undefined != true
  1422. undefined != false
  1423. * Boolean([]) == true
  1424. [] != true
  1425. [] == false
  1426. * Boolean({}) == true
  1427. {} != true
  1428. {} != false
  1429. 条件(三元)操作符(?:)
  1430. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1431. 以下这种写法可以三元操作符替换:
  1432. ::
  1433. if (val != 0) {
  1434. return foo();
  1435. } else {
  1436. return bar();
  1437. }
  1438. 你可以这样写来代替:
  1439. ::
  1440. return val ? foo() : bar();
  1441. 三元操作符在生成HTML代码时也是很有用的:
  1442. ::
  1443. var html = '<input type="checkbox"' +
  1444. (isChecked ? ' checked' : '') +
  1445. (isEnabled ? '' : ' disabled') +
  1446. ' name="foo">';
  1447. && 和 ||
  1448. ~~~~~~~~~~~~
  1449. 二元布尔操作符是可短路的,,只有在必要时才会计算到最后一项。
  1450. "||" 被称作为 'default' 操作符,因为可以这样:
  1451. ::
  1452. /** @param {*=} opt_win */
  1453. function foo(opt_win) {
  1454. var win;
  1455. if (opt_win) {
  1456. win = opt_win;
  1457. } else {
  1458. win = window;
  1459. }
  1460. // ...
  1461. }
  1462. 你可以这样写:
  1463. ::
  1464. /** @param {*=} opt_win */
  1465. function foo(opt_win) {
  1466. var win = opt_win || window;
  1467. // ...
  1468. }
  1469. "&&" 也可以用来缩减代码。例如,以下这种写法可以被缩减:
  1470. ::
  1471. if (node) {
  1472. if (node.kids) {
  1473. if (node.kids[index]) {
  1474. foo(node.kids[index]);
  1475. }
  1476. }
  1477. }
  1478. 你可以这样写:
  1479. ::
  1480. if (node && node.kids && node.kids[index]) {
  1481. foo(node.kids[index]);
  1482. }
  1483. 或者这样写:
  1484. ::
  1485. var kid = node && node.kids && node.kids[index];
  1486. if (kid) {
  1487. foo(kid);
  1488. }
  1489. 然而以下这样写就有点过头了:
  1490. ::
  1491. node && node.kids && node.kids[index] && foo(node.kids[index]);
  1492. 遍历节点列表
  1493. ~~~~~~~~~~~~~~~~
  1494. 节点列表是通过给节点迭代器加一个过滤器来实现的。这表示获取他的属性,如length的时间复杂度为O(n),通过length来遍历整个列表需要O(n^2)。
  1495. ::
  1496. var paragraphs = document.getElementsByTagName('p');
  1497. for (var i = 0; i < paragraphs.length; i++) {
  1498. doSomething(paragraphs[i]);
  1499. }
  1500. 这样写更好:
  1501. ::
  1502. var paragraphs = document.getElementsByTagName('p');
  1503. for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) {
  1504. doSomething(paragraph);
  1505. }
  1506. 这种方法对所有的集合和数组(只要数组不包含被认为是false值的元素) 都适用。
  1507. 在上面的例子中,你也可以通过firstChild和nextSibling属性来遍历子节点。
  1508. ::
  1509. var parentNode = document.getElementById('foo');
  1510. for (var child = parentNode.firstChild; child; child = child.nextSibling) {
  1511. doSomething(child);
  1512. }