【JS】ES6---基础3 promise与class重点

一、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的父类

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

羊️里个雲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值