微信小程序支持绝大部分ES6的新增特性。
Constants(常量)
ES6新增了const关键字,用来声明常量,一旦声明,常量的值就不能改变了。
- const PI = 3.141593;
- console.log(PI);
- PI = 3; // 报错: Uncaught TypeError: Assignment to constant variable.
- const PI = 3.1; // 报错: Uncaught SyntaxError: Identifier 'PI' has already been declared
Scoping(作用域)
ES6新增了let关键字,用来声明变量,但声明的作用只在代码块内有效。
- {
- let a = 10;
- var b = 1;
- }
- console.log(a); // 报错: Uncaught ReferenceError: a is not defined
- console.log(b); // 输出: 1
- for (let i = 0; i < 5; i++) {
- console.log(i);
- }
- console.log(i) // 报错: ReferenceError: i is not defined
let为JavaScript新增了块级作用域。
- function test() {
- let x = 1;
- let y = 2;
- {
- let x = 10;
- let y = 20;
- }
- console.log(x, y);
- }
- test(); // 输出: 1 2
Arrow Functions(箭头函数)
箭头函数是ES6在语法上提供的一个很好的特性,其特点有:
* 语法更为简洁了。
* 文法上的固定this对象。
一个参数
- let square = (x) => x * x;
- console.log('5 * 5 = ', square(5)); // 输出: 5 * 5 = 25
- let add = (x, y) => x + y;
- console.log('2 + 3 = ', add(2, 3)); // 输出: 2 + 3 = 5
- let total = () => square(add(5, 3));
- console.log(
- '(5 + 3)*(5 + 3) = ', total()); // 输出: (5 + 3)*(5 + 3) = 64
- var array = [1, 2, 3];
- array.forEach(v => console.log(v)); // 输出: 1 2 3
- var bob = {
- _name: "Bob",
- _friends: ['Tom', 'Jerry'],
- printFriends() {
- this._friends.forEach(f =>
- console.log(this._name + " knows " + f));
- }
- }
- bob.printFriends(); // 输出: Bob knows Tom Bob knows Jerry
允许为函数的参数设置默认值,即直接写在参数定义的后面。
- function logName(name = 'Unknown') {
- console.log('Name: ', name);
- }
- logName(); // 输出:Unknown
- logName('JavaScript'); // 输出:JavaScript
- function add(...numArray) {
- let sum = 0;
- for (let num of numArray) {
- sum += num;
- }
- return sum;
- }
- console.log(add(1, 2, 3)); // 输出:6
- console.log(add(1, 2, 3, 4, 5)); // 输出:15
- function add(x, y, z) {
- return x + y + z;
- }
- console.log(add(...[1, 2, 3])); // 输出:6
- console.log(add(...[3, 4, 5])); // 输出:12
完整代码:https://github.com/guyoung/GyWxappCases/tree/master/ES6