es6补充

es6新特性一览表

目录

  1. 箭头函数
  2. 字符串模板
  3. 模块化

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}`);

结果2
字符串模板的优点:

  1. 可以换行(美化代码)
  2. 字符串模板简化了字符串拼接
“姓名:“ + 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';
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值