推荐编码规范
下面是 Cocos Creator 开发团队使用的编码规范,收录在手册里以供游戏开发者和工具开发者参考。
命名规范
- 当我们为变量, 函数和实例命名时, 使用 camelCase 命名法.
// badvar FOOBar = {};var foo_bar = {};function FOOBar () {}// goodvar fooBar = {};function fooBar () {}
- 当我们为类或者模块命名时, 使用 PascalCase 命名法.
// badvar foobar = cc.Class({ foo: 'foo', bar: 'bar',});var foobar = require('foo-bar');// goodvar FooBar = cc.Class({ foo: 'foo', bar: 'bar',});var FooBar = require('foo-bar');
_当我们为私有属性命名
// badthis.__firstName__ = 'foobar';this.firstName_ = 'foobar';// goodthis._firstName = 'foobar';
- 文件名我们采用 dash 命名法
// badfooBar.jsFooBar.js// goodfoo-bar.js
语法规范
{}创建一个 object
// badvar obj = new Object();// goodvar obj = {};
[]创建一个 array
// badvar array = new Array();// goodvar array = [];
''来定义 string
// badvar str = "Hello World";// goodvar str = 'Hello World';
+定义
// bad const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'; // bad const errorMessage = 'This is a super long error that was thrown because \ of Batman. When you stop to think about how Batman had anything to do \ with this, you would get nowhere \ fast.'; // good const errorMessage = 'This is a super long error that was thrown because ' + 'of Batman. When you stop to think about how Batman had anything to do ' + 'with this, you would get nowhere fast.';
// badfunction() {∙var name;}// very badfunction() {∙∙<tab>∙∙var name;}// goodfunction() {∙∙var name;}// goodfunction() {∙∙∙∙var name;}
{和表达式放在同一行
// badif ( isFoobar ){}// goodif ( isFoobar ) {}// badfunction foobar(){}// goodfunction foobar() {}// badvar obj ={ foo: 'foo', bar: 'bar',}// goodvar obj = { foo: 'foo', bar: 'bar',}
{前请空一格
// badfunction test(){ console.log('test');}// goodfunction test() { console.log('test');}// baddog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog',});// gooddog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog',});
if,while) 的(前请空一格
// bad if(isJedi) { fight (); } // good if (isJedi) { fight(); }
- operator 之间请空一格
// badvar x=y+5;// goodvar x = y + 5;
- 在 Block 定义之间请空一行
// badif (foo) { return bar;}return baz;// goodif (foo) { return bar;}return baz;// badconst obj = { foo() { }, bar() { },};return obj;// goodconst obj = { foo() { }, bar() { },};return obj;// badconst arr = [ function foo() { }, function bar() { },];return arr;// goodconst arr = [ function foo() { }, function bar() { },];return arr;
- 不要使用前置逗号定义
// badvar story = [ once , upon , aTime];// goodvar story = [ once, upon, aTime,];// badvar hero = { firstName: 'Ada' , lastName: 'Lovelace' , birthYear: 1815 , superPower: 'computers'};// goodvar hero = { firstName: 'Ada', lastName: 'Lovelace', birthYear: 1815, superPower: 'computers',};
参考
airbnb/es5
