When should I name things with initial capital letters?

拜拜、爱过 提交于 2019-12-18 12:54:18

问题


I have always wondered when to use identifiers (for example, functions) with capital first letter instead of camel case. I always write my JS in camel case like this:

function doStuff() {}

var simpleVar = 'some stuff',
    myAry = [],
    myObj = {};

... But I know I am supposed to name some things with capital first letters. I just don't know WHEN this rule applies. Hope somebody can make things a bit clearer to me.


回答1:


According to the book "Javascript: the good parts", you should only capitalise the first character of the name of a function when you need to construct the object by "new" keyword.

This is called "the Constructor Invocation Pattern", a way to inherits.




回答2:


The convention is to name constructor functions (i.e. functions that will be used with the new keyword) with starting capital.

function MyType(simpleVar) {
    this.simpleVar = simpleVar;
}

myObject = new MyType(42);



回答3:


The name convention states that class names are named with a first capital letter, I'm not sure how it's like with javascript, which is a prototype based language, but basically it's

class ClassName
var varName
function funcName()


来源:https://stackoverflow.com/questions/8687223/when-should-i-name-things-with-initial-capital-letters

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