Capitalization convention for JavaScript objects

落爺英雄遲暮 提交于 2019-11-29 05:37:39

问题


I know this question has no answer, but I'm curious to know what other people think.

In a language like Java, it's a convention to begin classes with capital letters, and objects with lowercase letters. But what about JavaScript, where everything is an object?

I've seen some people suggest capitalizing only objects that are treated as classes; i.e. function objects with a prototype, that are intended to be used with the new operator. Instances of those objects would be lowercased.

That sounds logical. But what do you do about "global objects", where there's only one instance? Most people seem to capitalize these (for example, Math or Ext.History). This intuitively feels right, but it's hard to justify it with a consistent rule.

And what about objects that are used as namespaces? These seem to be all over the map: YUI, Ext.util, jQuery, etc.

Please provide secular rationalizations for your heart-felt religious views.


回答1:


You can follow this Google JavaScript Style Guide

In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.




回答2:


The convention is that there is no convention. Do what you want, just be consistent. I suggest follow Java style and ignore whatever convention the library (dojo, Ext, YUI, $, etc) you happen to be using is following.




回答3:


I agree with the capitalization of functions that define "classes" (air-quotes used) that in turn will be instanciated later using the new operator.

But that's it. Global objects are just global. Name them what you want.

All I would make sure is that they are unique and descriptive enough that they won't be overwritten accidentally by another developer at a later date.




回答4:


As recommended by Douglas Crockford:

"Constructor functions that must be used with the new prefix should start with a capital letter. JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted. Bad things can happen if new is missing, so the capitalization convention is an important defense."

https://www.crockford.com/code.html



来源:https://stackoverflow.com/questions/1540763/capitalization-convention-for-javascript-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!