RainZhai / rainzhai.github.com

宅鱼
http://rainzhai.github.io
Apache License 2.0
2 stars 0 forks source link

ES6核心特性 #9

Open RainZhai opened 7 years ago

RainZhai commented 7 years ago

ES6最常用的特性

let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments let,const 用于声明变量 let命令所在的代码块内有效

  if(1){ let a = 0; } 
  console.log(a);//显示Uncaught ReferenceError: a is not defined

let可以避免用来计数的循环变量泄露为全局变量

var a = [];
for (let i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 6

const也用来声明常量。一旦声明,常量的值就不能改变。

const WIDTH = 100; 
WIDTH = 2;//Uncaught TypeError: Assignment to constant variable.

class, extends, super

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        console.log(this.type + ' says ' + say)
    }
}
let animal = new Animal()
animal.says('hello') //animal says hello
class Cat extends Animal {
    constructor(){
        super()
        this.type = 'cat'
    }
}
let cat = new Cat()
cat.says('hello') //cat says hello

constructor就是构造方法,而this关键字则代表实例对象。constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实例对象可以共享的。

Class之间可以通过extends关键字实现继承,上面定义了一个Cat类,该类通过extends关键字,继承了Animal类的所有属性和方法。

super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。

ES6的继承机制,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this。

arrow function

简化了function写法

function(i){ return i + 1; } //常用写法
(i) => i + 1 //ES6
function(x, y) { 
    x++;
    y--;
    return x + y;
}//常用写法
(x, y) => {x++; y--; return x+y} //ES6

解决this指向问题,箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。 并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。

        setTimeout( () => {
            console.log(this.type + ' says ' + say)
        }, 1000)

template string

用反引号(`)来标识起始,用${}来引用变量,而且所有的空格和缩进都会被保留在输出之中

var user = {name: "boo"}; 
alert(`hello ${user.name}`);

destructuring

ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。

var [a,b,c] = [1,2,3];
var {foo,bar} = {foo:'aaa',bar:'bbb'}

default, rest

default很简单,意思就是默认值。大家可以看下面的例子,调用animal()方法时忘了传参数,传统的做法就是加上这一句type = type || 'cat'来指定默认值。

//传统写法
function animal(type){
    type = type || 'cat'  
    console.log(type)
}
animal()
//es6
function animal(type = 'cat'){
    console.log(type)
}
animal()
//rest参数(不定参数)
function animals(...types){
    console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]