javascript 我什么时候应该用首字母大写命名事物?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8687223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:13:42  来源:igfitidea点击:

When should I name things with initial capital letters?

javascriptnaming-conventions

提问by patad

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

我一直想知道何时使用首字母大写而不是驼峰式的标识符(例如,函数)。我总是像这样在驼峰式案例中编写我的 JS:

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.

...但我知道我应该用大写的第一个字母命名一些东西。我只是不知道这条规则何时适用。希望有人能让我更清楚一些。

回答by louis.luo

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.

根据“Javascript:好的部分”一书,当您需要通过“new”关键字构造对象时,您应该只将函数名称的第一个字符大写。

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

这称为“构造函数调用模式”,是一种继承方式。

回答by Peter-Paul van Gemerden

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

约定是用起始大写命名构造函数(即将与new关键字一起使用的函数)。

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

myObject = new MyType(42);

回答by Madara's Ghost

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

命名约定规定类名用第一个大写字母命名,我不确定它是如何使用基于原型的语言 javascript 的,但基本上它是

class ClassName
var varName
function funcName()