Cocos引擎TypeScript/JavaScript编码规范详解

Cocos引擎TypeScript/JavaScript编码规范详解

【免费下载链接】cocos-engine Cocos simplifies game creation and distribution with Cocos Creator, a free, open-source, cross-platform game engine. Empowering millions of developers to create high-performance, engaging 2D/3D games and instant web entertainment. 【免费下载链接】cocos-engine 项目地址: https://gitcode.com/GitHub_Trending/co/cocos-engine

前言

在Cocos引擎开发过程中,统一的编码规范对于保证代码质量、提升团队协作效率至关重要。本文将详细介绍Cocos引擎项目中TypeScript和JavaScript的编码规范,帮助开发者编写更规范、更易维护的代码。

命名规范

变量与函数命名

Cocos引擎采用**小驼峰式(camelCase)**命名法作为变量、函数和实例的主要命名方式:

// 不推荐
let FOOBar = {};
let foo_bar = {};
function FOOBar() {}

// 推荐
let fooBar = {};
function fooBar() {}

缩略词处理

当名称中包含缩略词时,需要特别注意大小写规则:

  1. 如果名称以缩略词开头,则全部小写
  2. 如果缩略词在名称中间或结尾,则全部大写
// 不推荐
let Id = 0;
let iD = 0;
function requireId() {}

// 推荐
let id = 0;          // 缩略词开头,全部小写
let uuid = '';       // 缩略词开头,全部小写
function requireID() {}  // 缩略词在结尾,全部大写
class AssetUUID {}    // 缩略词在中间,全部大写

类与模块命名

对于类和模块,Cocos引擎采用**大驼峰式(PascalCase)**命名法:

// 不推荐
let foobar = cc.Class({
    foo: 'foo',
    bar: 'bar',
});

// 推荐
let FooBar = cc.Class({
    foo: 'foo',
    bar: 'bar',
});

常量命名

常量使用全大写字母,单词间以下划线分隔:

// 不推荐
const privateVariable = 'should be uppercase';

// 推荐
const API_KEY = 'SOMEKEY';
const MAX_COUNT = 100;

私有成员命名

私有成员变量和方法使用下划线_作为前缀:

class Player {
    private _health: number;  // 私有属性
    private _calculateDamage() {}  // 私有方法
}

文件命名

TypeScript文件名应使用小写字母,单词间用短横线连接:

// 不推荐
FooBar.ts
fooBar.ts

// 推荐
foo-bar.ts
player-controller.ts

访问器设计规范

Cocos引擎对属性访问器有以下设计建议:

  1. 简单属性:直接声明为public属性

    // 推荐
    class Vector3 {
        public x: number;
        public y: number;
        public z: number;
    }
    
  2. 复杂逻辑属性:使用get/set方法

    class Player {
        private _health: number;
    
        getHealth(): number {
            // 可能有复杂计算逻辑
            return this.calculateEffectiveHealth();
        }
    
        setHealth(value: number): void {
            this._health = value;
            this.updateHealthBar();
        }
    }
    
  3. 影响其他数据的属性:使用get/set方法

    class PhysicsBody {
        private _velocity: number;
        private _damping: number;
    
        setVelocity(value: number): void {
            this._velocity = value;
            this._damping = this.calculateDamping();
        }
    }
    

语法规范

类属性声明

为了避免TypeScript编译后的性能问题,推荐以下做法:

// 不推荐 - 可能导致类型变化
class A {
    public a: number;
    constructor(a: number) {
        this.a = a;
    }
}

// 推荐 - 初始化默认值
class B {
    public b: number = 0;
    constructor(b: number) {
        this.b = b;
    }
}

// 最佳实践 - 使用declare
class C {
    public declare c: number;
    constructor(c: number) {
        this.c = c;
    }
}

字典对象创建

对于需要频繁增删属性的字典对象,推荐使用Object.create(null)

// 不推荐
let map1 = {};
let map2 = new Object();

// 推荐
let map = Object.create(null);  // 创建一个纯净对象,不继承Object原型

比较运算符

始终使用严格相等===和严格不等!==

// 不推荐
if (value == 10) { ... }

// 推荐
if (value === 10) { ... }

代码格式规范

缩进与空格

  1. 使用4个空格作为缩进
  2. 操作符前后保留空格
  3. 控制语句关键字后保留空格
// 不推荐
if(isJedi){
    fight();
}

// 推荐
if (isJedi) {
    fight();
}

// 不推荐
let x=y+5;

// 推荐
let x = y + 5;

大括号风格

  1. 左大括号不换行
  2. 左大括号前保留一个空格
// 不推荐
function foo() 
{
    // ...
}

// 推荐
function foo() {
    // ...
}

分号使用

始终在语句末尾添加分号:

// 不推荐
function foo() {
    return 'bar'
}

// 推荐
function foo() {
    return 'bar';
}

空行规则

在代码块之间保留空行以提高可读性:

// 不推荐
function update() {
    if (condition) {
        doSomething();
    }
    return result;
}

// 推荐
function update() {
    if (condition) {
        doSomething();
    }

    return result;
}

注释规范

单行注释

// 这是单行注释
const value = 10;  // 行尾注释

多行注释

/*
 * 这是多行注释
 * 第二行注释
 */

文档注释

使用JSDoc风格的文档注释:

/**
 * 计算两个向量的点积
 * @param v1 第一个向量
 * @param v2 第二个向量
 * @returns 点积结果
 */
function dotProduct(v1: Vector3, v2: Vector3): number {
    // ...
}

函数定义规范

函数声明

// 不推荐
const foo = function() {
    // ...
};

// 推荐
function foo() {
    // ...
}

箭头函数

// 不推荐
array.map(x=>x + 1);
array.map(x => {
    return x + 1;
});

// 推荐
array.map(x => x + 1);  // 单行简单函数
array.map(x => {        // 多行复杂函数
    const y = x * 2;
    return y + 1;
});

方法简写

// 不推荐
const obj = {
    foo: function() {
        // ...
    }
};

// 推荐
const obj = {
    foo() {
        // ...
    }
};

结语

遵循统一的编码规范是团队协作的基础,也是保证代码质量的重要手段。本文介绍的Cocos引擎TypeScript/JavaScript编码规范,涵盖了命名、语法、格式等多个方面,希望能帮助开发者编写出更规范、更易维护的代码。在实际开发中,建议结合ESLint等工具进行代码检查,确保规范得到有效执行。

【免费下载链接】cocos-engine Cocos simplifies game creation and distribution with Cocos Creator, a free, open-source, cross-platform game engine. Empowering millions of developers to create high-performance, engaging 2D/3D games and instant web entertainment. 【免费下载链接】cocos-engine 项目地址: https://gitcode.com/GitHub_Trending/co/cocos-engine

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值