ES6 二
9、迭代器(为了讲生成器)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>迭代器</title> </head> <body> <script> // Iterator // 是一种新的遍历机制,两个核心 // 1.迭代器是一个接口,能快捷的访问数据,通过Symbol.iterator来创建迭代器 通过迭代器的next()获取迭代之后的结果 // 2.迭代器是用于遍历数据结构的指针(数据库的游标) // 使用迭代 const items = ['one', 'two', 'three']; // 1.创建新的迭代器 const ite = items[Symbol.iterator](); console.log(ite.next()); //{value: "one", done: false} done如果为false表示遍历继续 如果为true表示遍历完成 console.log(ite.next()); console.log(ite.next()); console.log(ite.next()); </script> </body> </html>
10、生成器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>生成器 Generator</title> </head> <body> <script> // generator函数 可以通过yield关键字,将函数挂起,为了改变执行流提供了可能,同时为了做异步编程提供了方案 // 它普通函数的区别 // 1.function后面 函数名之前有个* // 2.只能在函数内部使用yield表达式,让函数挂起 // 构造生成器 /* function* func() { console.log('one'); yield 2; // 挂起 console.log('two'); yield 3; console.log('end'); } // 返回一个遍历器对象 可以调用next() let fn = func(); // console.log(o) console.log(fn.next());// 2 done:flase console.log(fn.next());// 3 done:flase console.log(fn.next()); // undefind done:true*/ // 总结:generator函数是分段执行的,yield语句是暂停执行 而next()恢复执行 function* add() { console.log('start'); let x = yield '2'; // x 可真的不是yield '2'的返回值,它是next()调用 恢复当前yield()执行传入的实参 console.log('one:'+x);// let y = yield '3'; console.log('two:'+y); return x+y; } const fn = add(); // 返回一个生成器函数 console.log(fn.next()); //{value:'2',done:false} console.log(fn.next(20)); //{value:'3',done:false} 会给当前x赋值20 console.log(fn.next(30)); //{value:50,done:true} 50 是通过return 来的 // 使用场景1:为不具备Interator迭代器接口的对象提供了遍历操作 // 生成器objectEntries(obj) function* objectEntries(obj) { // 获取对象的所有的key保存到数组 [name,age] const propKeys = Object.keys(obj); for(const propkey of propKeys){ yield [propkey,obj[propkey]] } } // 对象 const obj = { name:'小马哥', age:18 } obj[Symbol.iterator] = objectEntries; //objectEntries 这个函数通过生成器构造 console.log(obj); //age:18 name:'小马哥' Symbol(Symbol.iterator):f*objectEntries // obj迭代器生成就可以遍历 for(let [key,value] of objectEntries(obj)){ console.log(`${key}:${value}`); } </script> </body> </html>
11、Generator生成器的应用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>11 Generator的应用</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> </head> <body> <script> // Generator 部署ajax操作,让异步代码同步化 // 回调地狱(无限循环一直调用) 用生成器解决这个问题 // 发送请求 /* $.ajax({ url: 'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976', method: 'get', success(res) { console.log(res); // 继续发送请求 $.ajax({ url: '', method: 'get', success(res1) { // 又发送ajax $.ajax({ url: '', method: 'get', success(res2) { // 再在发送ajax $ } }) } }) } }) */ //例如1 // 生成器解决上面的问题 // 异步操作 /* function* main() { console.log('main'); // 请求传当前的url let res = yield request( 'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976' ) console.log(res); // 执行后面的操作 console.log('数据请求完成,可以继续操作'); } const ite = main(); ite.next(); function request(url) { $.ajax({ url, method: 'get', success(res) { ite.next(res); //调用next } }) } */ // 例如2 // 加载loading...页面 // 数据加载完成...(异步操作) // loading关闭掉 function* load() { loadUI(); //第一件事 yield showData(); // 第二件事 hideUI(); // 调用完next 后做的第三件事 } let itLoad = load(); itLoad.next(); // 这步执行showData() function loadUI() { console.log('加载loading...页面'); } function showData() { // 模拟异步操作 setTimeout(() => { console.log('数据加载完成'); itLoad.next(); // 等第二件事做完 调用next 做第三件事 }, 1000); } function hideUI() { console.log('隐藏loading...页面'); } </script> </body> </html>
12、Promise 对象和其方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> </head> <body> <script> // ES6提供三种异步方法 (Generator、Promise、async) // Promise 承诺 (就是一个对象) // 相当于一个容器,保存着未来才会结束的事件(通常是异步操作)的一个结果 // 各种异步操作都可以用同样的方法进行处理 axios(一个ajx库) // Promise两个特点: // 1.对象的状态不受外界影响 处理异步操作 三个状态 Pending(进行) Resolved(成功) Rejected(失败) // 2.一旦状态改变(从Pending到Resolved或者从Pending到Rejected),就不会再变(要么成功要么失败),任何时候都可以得到这个结果 /* let pro = new Promise(function(resolved,rejected) { //执行异步操作 let res = { code: 201, //成功 data:{ name:'小马哥' }, error:'失败了' } setTimeout(() => { // 模拟异步操作行为 if(res.code === 200){ //判断是否成功 resolved(res.data); }else{ rejected(res.error); } }, 1000); }) console.log(pro); // Promise 对象 里面又then方法和当前状态等等 pro.then((val)=>{ // then方法 接收执行异步操作完成之后返回的结果 console.log(val); // val 就是接受resolved(res.data)成功回来的值(name:小马哥) },(err)=>{ console.log(err); }); */ // 封装异步操作 /* function timeOut(ms) {// 超时时间毫秒级 return new Promise((resolved,rejected)=>{ setTimeout(() => { resolved('hello promise success!!') }, ms); }) } timeOut(2000).then((val)=>{ // 2000毫秒后点then返回想要的val成功结果 console.log(val); }) */ // 具体应用 //一个url // https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976 // const getJSON = function (url) { // return new Promise((resolve, reject) => { // const xhr = new XMLHttpRequest(); // xhr.open('GET', url); // xhr.onreadystatechange = handler; // xhr.responseType = 'json'; // xhr.setRequestHeader('Accept', 'application/json'); // // 发送 // xhr.send(); // function handler() { // if (this.readyState === 4) { // if (this.status === 200) { // resolve(this.response.HeWeather6); // } else { // reject(new Error(this.statusText)); // } // } // } // }) // } // 这个不太好 用下面的最终结果catch的 // let a = getJSON( // 'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976') // .then((data) => { // 调用完getJSON方法之后返回一个Promise对象 接收成功回调回来的结果 // // console.log(data); // return data[0] // }).then((obj)=>{ // 接收error // console.log(obj); // }) // console.log(a); // 以下来个方法等价 then获取error不太友好 使用catch /* catch(err=>{ }) // then(null,err=>{ // 获取error 与上面的catch是等价的 // }) */ // 应用 最终的结果 // getJSON('https://free-ap.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976') // .then(data => { // console.log(data); // }).catch(err => { // console.log(err); // }) // then()方法 // then() 第一个参数是relove回调函数,第二个参数是可选的 是reject状态回调的函数 // then()返回一个新的promise实例,可以采用链式编程 // promise的其他方法 // resolve() reject() all() race() done() finally() // resolve()能将现有的任何对象转换成promise对象 // let p = Promise.resolve('foo'); // 把字符串转换成一个promise对象 // 以下 等价于 let p = Promise.resolve('foo'); 简化了很多代码 /* let p = new Promise(resolve=>resolve('foo')); p.then((data)=>{ console.log(data); // ‘foo’ }) */ // 应用:一些游戏类的素材比较多,等待图片、flash、静态资源文件 都加载完成 才进行页面的初始化 /* reject() let promise1 = new Promise((resolve, reject) => {}); let promise2 = new Promise((resolve, reject) => {}); let promise3 = new Promise((resolve, reject) => {}); // all() let p4 = Promise.all([promise1, promise2, promise3]) p4.then(()=>{ // 三个异步行为都成功 才成功 }).catch(err=>{ // 如果有一个失败 则失败 }) */ // race() 某个异步请求设置超时时间,并且在超时后执行相应的操作 // 1 请求图片资源 function requestImg(imgSrc) { return new Promise((resolve, reject) => { const img = new Image(); img.onload = function () { // 加载 resolve(img); } img.src = imgSrc; }); } // 2 请求图片超时函数 function timeout() { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('图片请求超时')); }, 3000); }) } // 通过race方法进行操作(第一个参数requestImg 第二个参数timeout) Promise.race([requestImg( 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1566364222518&di=b3c6d411bb23f17d1798fc6be3325ad5&imgtype=0&src=http%3A%2F%2Fpic.k73.com%2Fup%2Fsoft%2F2016%2F0102%2F092635_44907394.jpg'),timeout()]).then(data=>{ console.log(data); document.body.appendChild(data); }).catch(err=>{ // 超时就会走这个 console.log(err); }); //done() finally()会放到最后的 /* server.listen(3000).then(()=>{ }).finally(server.stop()); */ </script> </body> </html>
13、asyno的用法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>async异步操作</title> </head> <body> <script> //Generator Promise async async 1.解决回调地域 2.使得异步操作显得更加方便 // async // 作用:使得异步操作更加方便 // 基本操作 async它会返回一个Promise对象 .then .catch // async是Generator的一个语法糖 更加易于阅读 // 操作成功时 async function f() { // return await 'hello async'; let s = await 'hello world'; // 一次的异步行为 let data = await s.split(''); // 又是一次异步操作 等待上次结果完成后 return data; } // 接收结果 如果async函数中有多个await 那么then函数会等待所有的await指令 运行完的结果 才去执行 f().then(v => { console.log(v) }).catch(e => console.log(e)); // 操作失败时 async function f2() { // throw new Error('出错了'); try { await Promise.reject('出错了'); } catch (error) { } return await Promise.resolve('hello'); } f2().then(v => console.log(v)).catch(e => console.log(e)); // 需求: 想获取和风天气 现在now的数据 // getJSON操作 const getJSON = function (url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); // 发送 xhr.send(); function handler() { if (this.readyState === 4) { if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); } } } }) } // 异步操作封装 async function getNowWeather(url) { // 发送ajax 获取实况天气 let res = await getJSON(url); // 异步行为 等待getJSON结果出来 再进行处理 res是一个promise对象 console.log(res); // 获取HeWeather6的数据 获取未来3~7天的天气状况 let arr = await res.HeWeather6; // arr 一个数组 return arr[0].now; } getNowWeather( 'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976') .then(now => { // 获取最新天气数据 console.log(now); }) </script> </body> </html>
14、class类
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> // es5造类 /* function Person(name,age) { this.name = name; this.age = age; } Person.prototype.sayName = function() { return this.name; } let p1 = new Person('小马哥',28); console.log(p1); */ // ES6 类 class Person { // 实例化的时候会立即被调用 constructor(name, age) { this.name = name; this.age = age; } } // 单独添加方法 sayuame() { return this.uame }, sayuge() { return this.uge } // 通过Object.assign()方法一次性向类中添加多个方法 Object.assign(Person.prototype, { sayName() { return this.name }, sayAge() { return this.age } }) let p1 = new Person('小马哥', 28); console.log(p1); </script> </body> </html>
15、类的继承
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>类的继承</title> </head> <body> <script> // 使用关键字 extends class Animal{ constructor(name,age) { this.name = name; this.age = age; } sayName(){ return this.name; } sayAge(){ return this.age; } } class Dog extends Animal{ constructor(name,age,color) { super(name,age); // Animal.call(this,name,age); this.color = color; } // 子类自己的方法 sayColor(){ return `${this.name}是${this.age}岁了,它的颜色是${this.color}` } // 重写父类的方法 sayName(){ return this.name + super.sayAge() + this.color; } } let d1 = new Dog('小黄',28,'red'); console.log(d1.sayColor()); console.log(d1.sayName()); // 思考:如何让多个类 混入到一个类中???? </script> </body> </html>
16、export 抛出 和import 接收
// es6模块功能主要有两个命令构成:export和import
// export用于规定模块的对外接口 import用于输入其它模块提供的功能
// 一个模块就是独立的文件
//此文件是index.js 是exporty抛出变量个对象
/*
export const name = '张三';
export const age = 18;
export function sayName(){
return 'my name is 小马哥';
}
*/
// export sayName() 这种会报错 一定要加关键字 或大括号括起来
// export {sayName}
const name = '张三';
const age = 18;
function sayName() {
return 'my name is 小马哥';
}
export { // 这种用的比较多 可以一下抛出多个变量
name,age,sayName
}
/* const obj = {
foo:'foo'
} */
class Person{
constructor(){
}
sayAge(){
console.log('16');
}
}
export default Person; // 抛出对象
// 此文件是用户接收的 export抛出的
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script type='module'> // CommonJS和AMD // ES6 module import Person,{name,age,sayName} from './modules/index.js' // import * as f from './modules/index.js' // console.log(Person); const p = new Person(); p.sayAge(); // console.log(f.default); // console.log(name,age,sayName()); </script> </body> </html>

浙公网安备 33010602011771号