跳至正文

CocosCreator开发笔记(24)-Creator程序员应该掌握的一些ES6语法

  • Cocos

ES6,全称ECMAScript 6.0,是2015年6月发布的JavaScript 新一代语法标准。与之前版本相比,增加了很多有用的特性,使JavaScript代码更加优雅和可靠。

目前主流浏览器已经支持99%以上的ES6语法,所以我们也可放心的在Cocos Creator 2.x及更高版本中使用,下面简单列一些项目中常用、能提高开发效率的ES6特性。

1 箭头函数

箭头函数以极致优雅和简洁的方式来定义匿名函数,是个人最喜欢的ES6新增特性。

// ES5
node.schedule(function() {
    this.doSomething();
}.bind(this), 5);

// ES6
node.schedule(() => {
    this.doSometing();
}, 5);

2 let/const代替var

优先使用:const > let > var

const num; // Error
const num = 9999; // ok
let x = 0; // ok 

3 解构赋值

ES6允许按照一定模式,从数组和对象中提取值,对变量赋值,这个过程被称为解构。

3.1 数组的解构

let array = [1, 2, 3];
// ES5
let a = arr[0]; // 1
let b = arr[1]; // 2
let c = arr[2]; // 3
// ES6
let [a, b, c] = array; // 1, 2, 3

// ES5
let a = 1;
let b = 2;
let c = 3;
// ES6
let [a, b, c] = [1, 2, 3]

3.2 对象的解构

// ES5
let width = node.width;
let height = node.height;
// ES6
let { width, height } = node;

4 对象属性简写法

// ES6 定义对象
let obj = { x, y, z };
// 等同于 ES5
let path = { x:x, y:y, z:z };

5 函数参数默认值

calcTime(dt, bSelf = false) {
    ....
}

6 反引号/模板字符串

let name = 'Jack';
let num = 100;
let outStr = `${name} have ${num}?`;
cc.log(outStr); // Jack have 100

7 字符串长度补全

如果字符串不够指定长度,会在头部和尾部补全。
- padStart() 用于头部补全;
- padEnd() 用于尾部补全。

let s = '5';
s.padStart(2, '0'); // '05'
s.padEnd(2, '0'); // '50'

8 try...catch 异常处理

try {
    let arr = str.split('|');
    for (let i = 0, len = arr.length; i < len; i++) {
        obj[i] = parseFloat(arr[i]);
    }
} catch (e) {
    log.error('str is invalid');
}

9 其它建议

函数的可选参数集中在一个对象里,作为最后一个参数。

// 可选参数集中在config对象里
play(x1, x2, x3, config) {
    if (!!config && config.hasOwnProperty('scale')) {
        this.scale = scale;
    }
    if (!!config && config.hasOwnProperty('width')) {
        this.width = width;
    }
}

欢迎关注微信公众号“楚游香”,获取更多文章和交流。

标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注