1.ES6 中有 class 语法。值得注意是,这里的 class 不是新的对象继承模型,它只是原型链的语法糖表现形式。
函数中使用 static 关键词定义构造函数的的方法和属性:
class声明的本质是function
<script type="text/javascript">
// 创建一个类
class Animal{
constructor(name) {
this.name = name;
}
say(){
console.log("我开始怒吼!");
}
}
class Cat extends Animal{
constructor(name,color){
super(name);
this.color=color;
}
skill(){
console.log(`我的名字是${this.name}我是高贵的${this.color}`);
console.log("我的任务是要到小鱼干");
}
}
// 实例化类=类(实例化对象)
var c1 = new Cat("小花","花白色");
var c2 = new Cat("小白","白色");
</script>
2.模块化:如果要进行模块化操作,需要引入第三方的类库。ES6的模块化分为导出(export)与导入(import)两个模块。
需要条件:
1. 有http服务器
2.script的type类型需要改为module <script type="module">
3.要有js文件 ./utils.js
在js文件中需要使用export导出 一个文件只能导出一个默认函数
//在js文件中写如下代码
var name = "整日发愁";
// 导出name
// export {name}
function fun (){
console.log("我叫"+name);
}
// 导出函数
export{name,fun}
// 导出默认
class Cat {
constructor(name) {
this.name=name
}
}
export default Cat;
在<script type="module"></script>中使用import导入
<script type="module">
// 导入全部 起一个别名叫utils 从 url
import * as utils from './js/utils.js'
console.log(utils.name);
utils.fun();
// 使用默认
var c2 = new utils.default("整日发愁");
console.log(c2)
</script>
3.es6中有简单去重方法Set 但只能处理简单的数据 不过很方便
<script type="text/javascript">
var arr = [1,2,3,2,3,4,5,4];
arr = [...new Set(arr)];
console.log(arr);
</script>
4.for in 循环用于遍历数组,类数组或对象,ES6中新引入的for of循环功能相似,不同的是每次循环它提供的不是序号而是值,但是对象不能被for of遍历。
// keys 键的集合
for(let k of arr.keys()){
console.log(k);
}
// values 值的集合
for(let v of arr.values()){
console.log(v);
}
// entries 键与值的集合
for(let [k,v] of arr.entries()){
console.log(k,v);
}
5.ES6 对 Promise 有了原生的支持,一个 Promise 是一个等待被异步执行的对象,当它执行完成后,其状态会变成 resolved 或者rejected。Promise使用 .then(res=>console.log(res))成功兑现执行, .catch(err=>console.log(err))拒绝兑现执行
<script type="text/javascript">
// Promise 承诺 不会立即执行 主要做异步任务(需要时间等待) 任务
var p = new Promise((resolve,reject)=>{
setTimeout(()=>{
var n = Math.random();
if(n>0.5){
// 可以兑现
resolve("明天吃点肉");
}
else{
// 拒绝
reject("没钱不吃了");
}
},3000)
})
// 然后呢 p的使用
p.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
// .then 等待 凭据 p里的 resolve执行
// .catch 等待 凭据 p 里的 reject 执行
</script>
promise解决多次回调函数也是很简便的,方便了我们查找改错。
<script type="text/javascript">
// 创建函数
function say(msg,item){
// 给函数添加承诺并返回
return new Promise((resolve,reject)=>{
setTimeout(()=>resolve(msg),item)
})
}
say("可以认识一下吗",2000)
.then(res=>{
console.log(res);
// 返回函数执行承诺
return say("咱俩加个微信吧",3000);
})
.then(res=>{
console.log(res);
return say("你愿意给我一个机会做你对象吗?",5000);
})
.then(res=>{
console.log(res);
})
</script>
总结:class声明的本质是function,ES6的模块化分为导出(export)与导入(import)两个模块script的type类型要改为module,去重方法用Set,for of 遍历的输出为值,promise用处广泛解决回调简单。