<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模块化</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
/*----------ES6 Symbol & generator-----------*/
/*
* 数据类型:
* number、string、boolean....Symbol(新增类型)*/
/*Symbol
* 【注意】
* 1.Symbol 不能new
* 2.Symbol() 返回是一个唯一值
* 3.Symbol 作为属性 for in 循环不会出来
* */
{
let syml = Symbol('aaa'); //定义
//let sym2 = new Symbol('aaa'); // 报错Symbol is not a constructor
console.log(syml); //使用
console.log(typeof syml) // symbol
/*type 检测类型 7种
* number、string、boolean、Object、undefined、function、(symbol)新增
* */
// console.log(typeof null) // Object
let json = {
[syml]:1,
};
console.log(json[syml]) //1;
for(let key in json){
console.log(key); //Symbol 作为属性 for in 循环不会出来;
}
}
// ------ generator函数(生成器) ------
/*
* 【作用】解决异步 深度嵌套传值的问题,刚出很火。现在多用async代替
* 【语法】function * show(){
* yield 数据 // 生产
* }
* */
{
function * gen() {
yield 'welcome';
yield 'to';
return '牧马人'
}
let g1 = gen();
// console.log(g1); // Object gen
// console.log(g1.next()); // {value: "welcome", done: false}
// console.log(g1.next()); // {value: "to", done: false}
// console.log(g1.next()); // {value: "牧马人", done: true}
// console.log(g1.next()); // {value: undefined, done: true}
// 上述调用,手动调用,麻烦
// 配合 for..of
for (let key of g1){ //for ..of 自动遍历 generator函数
console.log(key); //只会返回 value return的东西不会遍历
}
//配合结构赋值
let [...a] = gen();
console.log(a); // ["welcome", "to"]
//配合扩展运算符
console.log(...gen()); // welcome to
//配合Array.from()
console.log(Array.from(gen())); // ["welcome", "to"]
//配合axios 模拟实战
{
// https://api.github.com/users/getSpidd
function * gen(){
let val = yield 'getSpidd'
console.log(val)
yield axios.get(`https://api.github.com/users/${val}`)
}
let g1 = gen();
let username = g1.next().value;
g1.next(username).value.then(res=>{
console.log(res)
})
}
}
</script>
</head>
<body>
<h1></h1>
</body>
</html>
网友评论