ES6

作者: YaoHoney | 来源:发表于2017-07-17 22:28 被阅读0次

介绍

ECMAScript 6 在接下来的一段时间内将成为 ECMAScript的一个标准。这个标准预计在今年的时候就会被签署,不管在Github,还是在很多社区,javascript爱好者已经早已开始拥抱变化,享受ES6 带来的美好,这篇文章将介绍ES6的一些新特性。由于ES6 还没有很好地被浏览器支持,所以这篇文章的ES6代码将使用 Babel 进行编译。
ECMAScript 6 的新特性

箭头(Arrow)

=>是function的简写形式,支持expression和 statement 两种形式。同时一点很重要的是它拥有词法作用域的this值,帮你很好的解决this的指向问题,这是一个很酷的方式,可以帮你减少一些代码的编写,先来看看它的语法。

 ([param] [, param]) => {
       statements
  }
  param => expression

类(class)

ES6 引入了class(类),让javascript的面向对象编程变得更加容易清晰和容易理解。类只是基于原型的面向对象模式的语法糖。

   class Animal { // 构造方法,实例化的时候将会被调用,如果不指定,那么会有一个不带参数的默认构造函数.
         constructor(name,color) {
          this.name = name;
         this.color = color;
          }
        // toString 是原型对象上的属性
          toString() {
                      console.log('name:' + this.name + ',color:' + this.color);
          }
}

 var animal = new Animal('dog','white');
 animal.toString();

 console.log(animal.hasOwnProperty('name')); //true
 console.log(animal.hasOwnProperty('toString')); // false
 console.log(animal.__proto__.hasOwnProperty('toString')); // true

 class Cat extends Animal {
         constructor(action) {
          // 子类必须要在constructor中指定super 方法,否则在新建实例的时候会报错.
          // 如果没有置顶consructor,默认带super方法的constructor将会被添加、
          super('cat','white');
          this.action = action;
}
 toString() {
        console.log(super.toString());
    }
}

 var cat = new Cat('catch')
 cat.toString();

 // 实例cat 是 Cat 和 Animal 的实例,和Es5完全一致。
  console.log(cat instanceof Cat); // true
 console.log(cat instanceof Animal); // true

相关文章

网友评论

      本文标题:ES6

      本文链接:https://www.haomeiwen.com/subject/bigqkxtx.html