一、promise
1.基础
js是单线程的语言,所以很多操作都是异步操作,而异步操作多由回调函数完成,这里边就会引出一个现象”回调地狱"即回调函数中有回调函数,这种现象会导致代码的可读性降低,为了解决这个问题我们选择使用promise
1.1作用:
防止出现回调地狱,提高代码的可读性,像同步操作那样去执行异步操作
Let pro=new Promise(function(resolve,reject){
Console.log(“start”);
Resove(“ok ok”)
Console.log(“end”);
});
Pro.then(function(data){
Console.log(data);
})
1.2 必须接受一个函数作为参数,俩个参数名不是自定义的,是必须这么写的
2.原理
一个promise对象就代表一个异步操作,通过状态去管理异步操作
1.1状态:
Pending: 执行中
Fulfilled: 完成,也就执行了resolve( )
Rejected: 失败,reject( )执行
1.2常见写法(放到function中使用)
funtion timeOut( ){
let randNum=Mayh.random( )*2;
console.log(randNum)
return new Promise(function(resolve,reject){
setTimeout(function( ){
if(randNum>1){
resolve( );
}else{
reject( );
}
},randNum*1000);
});
}
timeOut( ).then(function( ){
console.log(“ok”)
},function( ){
console.log(“no”)
});
十三、Class
1.ES5***********************************
Function Point(x,y){
This.x=y;
This.y=y;
}
Point.prototype.toString=function( ){ }
Var p=new Point(100,100);
ES6***********************************
Class Point{
//构造函数
This.x=y;
This.y=y;
}
toString( ){ }
}
Let p=new Point(100,100);
2.特点:
必须包含constructor
属性添加到constructor中
class的本质仍然是构造函数
This 指向class的实例
3.静态方法
使用构造函数(class)调用
class Point{
constructor(x,y){
//构造函数
this.x=y;
this.y=y;
}
static toString( ){
//静态方法
}
}
4.继承
class Ball{
constructor(x,y){
this.x=y;
this.y=y;
}
getX( ){
console.log(this.x);
getY( ){
console.log(this.y);
}
}
class ColorBall extends Ball{
constructor(x,y,color){
super(x,y);
this.color=color;
}
getX( ){
//如果与父类同名匿名会覆盖父级方法
console.log(this.X*2);
}
getColor( ){
console.log(this.color);
}
}
5.继承原生js的构造函数
Class MyArray extends Array{ }
Let arr=new MyArray( );
6.Object.getPrototypeOf(x): 获取x的父类