目录
- 箭头函数
- 字符串模板
- 模块化
1.箭头函数
箭头函数是匿名函数的简化版
箭头函数能保存this的指向对象(this所在的上一级上下文环境)
(i,j)=>{
}
let obj = {
name1: '张三',
name2: '李四',
say: function() {
console.log(this.name1); //张三 (this指向obj)
},
// say: () => {
// console.log(this.name1); //undefined (this指向{})
// },
// sayYou: function() {
// setInterval(function() {
// console.log(this.name2); //undefined (this指向Timeout{....})
// }, 1000);
// }
sayYou: function() {
setInterval(() => {
console.log(this.name2); //李四 (this指向obj)
}, 1000);
}
}
obj.sayYou();
obj.say();
2.字符串模板
let name ='张三';
let sex = '男';
let age = 10;
console.log(`姓名:${name};性别:${sex};年龄:${age}`);
字符串模板的优点:
- 可以换行(美化代码)
- 字符串模板简化了字符串拼接
“姓名:“ + name + ”;性别:“ + sex + ”;年龄:“ + age
字符串模板(" ` “不是字符的” ’ ")=>
`姓名:${name};性别:${sex};年龄:${age}`
3.模块化
模块化(避免全局污染)
commonJS,AMD,CMD,es6 module
es6模块化大致步骤:
导入模块
<script src="a.js" type="module">
导入依赖的模块
导入默认函数
import xxx from 'b.js';
导入名为fff函数
import {fff} from 'b.js'
导入全部变量和函数
import * as obj from 'b.js'
模块书写
默认导出
export default function(){
}
普通导出
export var a=1;
export function fff(){
}
案例:
<!DOCTYPE html>
<html>
<head>
<title>es6模块化</title>
<script src="index.js" type="module"></script>
</head>
<body>
<h1 id="showH1"></h1>
</body>
</html>
index.js
import * as obj from "./a.js";
console.log(obj.ff());
document.querySelector('#showH1').innerText = obj.b;
a.js
import {show} from './aa.js'
export let a = 100;
export function ff() {
return a * a;
}
export let b = show();
aa.js
export function show() {
return 'hello es6';
}