一 Generator
- Generator:提供异步编程的解决方案,异步函数的写法;
- 标注:*;
- next,:调用遍历器方法,移动方法内部的指针。next返回一个对象,value指的是yield表达式的值:done:false(遍历还没有结束);done:true(遍历结束);
- Generator 函数返回的一个遍历器 ,就可以遍历;
function *method(){
yield 1;
yield 2;
yield 3;
yield 4;
}
for(let num of method()){
console.log(num);
}
- 如果Generator函数内部yield表达式内部有yield:
function *method(x,y){
yield x+(yield x+y);
}
let met=method(2,3);
console.log(met.next());
console.log(met.next().value);//NAN
console.log(met.next());
二 class
- class类的语法。 类的写法:使用类new,类的构造函数是在类的实例化时执行;在类里面封装方法,直接写就行;class类里面写的代码,在类对象的_proto_原型上面;类里面执行方法直接,对象点(对象点的方法 为非静态方法);
- Object.assign():给类上添加方法:
Object.assign(person.prototype,{
toValue: function () {
console.log("输出值");
}
})
- 类里面封装属性,在构造里面写this.***或者直接在class里面写属性是一样的。类里面的this,指针指向当前的类对象;
- 前端的类只能有一个构造函数;
- 类里面的getter setter访问器,拦截属性的存取行为。class类里面的get、set访问器,作用是在设置属性的时候,用访问器拦截该属性的行为;
- 字面量声明类的方法。属性表达式写法:
let method="SendData";
class person{
constructor(){
}
[method](){
}
}
let per=new person();
console.log(per);
- 类的表达式。下面的类名称可以省略:
let person=class me{
constructor(){
}
}
console.log(new person());
- 类的静态属性:static。类的静态方法是在方法前面添加static关键字:
static goHome(){
console.log("静态方法");
}
- class的非静态成员变量和非静态方法,是由类对象点的:per.toValue();静态方法是由类名称点的:Person.goHome();
- 静态方法特点:不会被实例继承;
- 类里面的私有方法和私有属性ES6并没有提供,只是认为变通的,私有方法自己可以区别;
- 私有属性ES6提供的方案是:在属性前面加 #:
class Person{
//私有属性
#count=0;
constructor(){
this.#count++;
}
toValue(){
console.log(this.#count);
}
}
let per=new Person();
per.toValue();
三 class继承
JS通过修改原型链实现继承,ES6里面通过extends实现继承,比之前更方便清晰。
- super函数使用方式:
super指向父类的构造,返回的是子类的实例;
super当做对象使用,指向的是父类的原型对象,在静态方法中指向父类;
四 module
script加载模块代码的时候写type=“module”。
- ES6自动采用严格模式—模块的到处:export;引入模块:import;
- 静态页面这样写,不识别。引入模块,export default暴露方式;