ES6学习笔记

655 阅读2分钟

ES 全称 ESMAScript , EMSAScript 是 ECMA 制定的标准化脚本语言。目前 JavaScript 使用的 ECMAScript 版本为 ECMA-417 。关于 ECMA 的最新资讯可以浏览 ECMA news 查看。

相比于ES5而言,ES6不仅使语法更加的简洁,也使得变量使用更加规范,在应用中减少了变量冲突使用或者污染等问题。除此之外,也提供了一些更简便的 api 。

ES6新特性(2015)

  • 模块化
  • 箭头函数
  • 函数参数默认值
  • 模板字符串
  • 结构赋值
  • 延展操作符
  • 对象属性简写
  • Promise
  • Let与Const

1.类(class)

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

let animal = new Animal('dog','white');//实例化Animal
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() {
        //子类必须要在 constructor 中指定 super 函数,否则在新建实例的时候会报错.
        //如果没有置顶 constructor ,默认带 super 函数的 constructor 将会被添加
        super('cat','white');
        this.action = action;
    }
    toString(){
        console.log(super.toString());
    }
}

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

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

2.模块化(Module)

ES5不支持原生的模块化,在ES6中模块作为重要的组成部分被添加进来。模块的功能主要由 export 和 import 组成。每一个模块都有自己单独的作用域,模块之间的相互调用关系是通过 export 来规定模块对外暴露的接口,通过import来引用其它模块提供的接口。同时还为模块创造了命名空间,防止函数的命名冲突

导出(export)

ES6允许在一个模块中使用 export 来导出多个变量或函数。

导出变量

//test.js
export var name = 'Rainbow'

心得:ES6不仅支持变量的导出,也支持常量的导出。export const sqrt = Math.sqrt;//导出常量

ES6 将一个文件视为一个模块,上面的模块通过 export 向外输出了一个变量。一个模块也可以同时往外面输出多个变量。

var name = 'Rainbow';
var age = '24';
export { name , age };

导出函数

//myModule.js
export function myModule(someArg) {
    return someArg;
}

导出(import)

定义好模块的输出以后就可以在另外一个模块通过 import 引用。

import {myModule} from 'myModule'; //main.js
import {name,age} from 'test'; //test.js

心得:一条 import 语句可以同时导入默认函数和其他变量。 import defaultMethod,{ otherMethod } from 'xxx.js'

3.箭头函数(Arrow Function)

待续...