ES6的学习(2)

84 阅读2分钟

ES6

对象

  1. 属性简写
  2. 动态简写
  3. 函数简写
  4. 继承

特点

  1. 用class声明 本质是function
  2. constructor 构造
  3. extends继承
  4. new实例化
  5. 类名建议大写

实例

    <script>
	class Cat extends Animal{	
          constructor(name,color){
            super(name);
            this.color = color;
	}
	say(){}
        }
        var c1 = new Cat("小猫猫","白白的")
    </script>

模块化

导出export

// 新建js文件并写入以下程序
var name = "陈陈";
// 导出name
function fun(){
	console.log("我叫"+name+"我是一只自由的小鸟","我的翅膀被折断了");
		
}
// 导出函数
export{name,fun};


class Cat {
	constructor(name) {
	    this.name = name;
	}
}
// 一个文件只能导出一个默认
export default Cat;
  1. export(name):导出一个
  2. export(name,fun):导出多个

导入import

<body>
     <!-- 新建html文件 -->
	 <!-- 注意:script的类型为module -->
    <script type="module">
		
		
		// 导入函数
                import Cat,{name,fun} from './js/utills.js'
		console.log(name);
		fun()
		
		// 导入默认
		// import Cat from './js/utills.js'
		var c1 = new Cat("小小只")
		console.log(c1);
		
		
		
		// 另一种导入方式
		import * as utills from './js/utills.js';
		console.log(utills.name);
		utills.fun()
		var c2 = new utills.default("白白")
		console.log(c2)
    </script>
</body>
  1. import {name,fun} from url
  2. 导入默认:import Cat from url
  3. 合并默认:import Cat,{name,fun} from url
  4. 导入所有 as关键字:import * as utils from url
  5. 文件打开必须是http协议,不能是 D: C: file协议

Set 集合

  1. 内容不重复
  2. 初始化:var s1 = new Set([1,1,2])
  3. 利用set 特性去重arr = [... new Set(arr)]true保留,false 不保留
  4. 常用方法:add 添加;delete 删除;clear 清空;has 检查是否有;size长度

WeakSet 集合

箭头函数是函数的简写方式

  1. 内容不重复,内容必须是引用对象
  2. new WeakSet([,,,])

Map 图

  1. 特点:键可以是任意类型
  2. 初始化:new Map([["zql",20], ["mumu",30], [8,200]])
  3. 方法:set 添加;get获取;has 检测;size 长度;delete 删除;clear清空
  4. 最大值,最小值

WeakMap

  1. 特点:key都是弱引用

可迭代对象

  1. 可以被for of遍历
  2. String 字符串;Array 数组;Set 集合;Map 图
  3. 使用:keys() 键集合;values() 值集合;enteries() 键与值集合
    <script>
        let arr = ["陈陈","小陈","cc","name"];
		for (c of arr){
			// console.log(c);
		}
		for (k of arr.keys()){
			// console.log(k);
		}
		for (v of arr.values()){
			// console.log(k);
		}
		for ([k,v] of arr.entries()){
			console.log(k,v);
		}
    </script>

Promiss

定义

执行异步任务,避免回调地狱

.then和.catch方法

    p.then(res=>console.log(res))
    .catch(err=>console.log(err))

其他

Promise.race([...]).then()异步列表中最resolve的值

封装Promise

    say("msg",500)
    .then(res=>{
       console.log(res)
      return say("abc",123)
    })
    .then(res=>console.log(res))

实例

    <script>
        function say((msg,time)=>{
			setTimeout(()=>resolve(msg),time)
		})
		say("你好",2000)
		.then(res=>{
			console.log(res);
			return say("你踩着我尾巴了",3000)
		})
		.then(res=>console.log(res))
    </script>