call,apply,bind的区别

  <!DOCTYPE html>

  <html lang="en">

  <head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>call,apply,bind的区别</title>

  </head>

  <body>

    <H1>你好</H1>

    <script>

      //1

      //  //call是一个方法,可以调用函数的方法

      // function fun(){

      //   console.log(this)//this指向windows

      //   console.log('hello')

      // }

      // fun.call(); //call直接调用了fun函数

     

      // 2 改变this的指向

      function fun(){

        console.log(this.name) //this指向windows

      }

      let cat={

        name:'mm'

      }

      fun.call(cat) //call调用函数'fun',并且把cat传进来,此时this.name===cat.name

      let dog={

        name:"旺财",

        sayName(){

        console.log("我是"+this.name);

        },

        eat(food){

          console.log('我喜欢吃'+food)

        }

      }

      dog.sayName();//我是旺财

      dog.sayName.call(cat) //我是mm,相当于call调用了函数sayname整个函数,把cat传进去了,this指向了cat

      dog.eat('骨头') //我喜欢吃骨头

      dog.eat.call(cat) //我喜欢吃undefined,需要传参

      dog.eat.call(cat,'鱼') //我喜欢吃鱼

      //3 apply 与call唯一的区别就是传参不一样,apply是通过数组传参

      dog.eat.call(cat,['鱼']) //我喜欢吃鱼

      //bind 传参和call一模一样,但是bind()方法不回调用函数

      let fun=dog.eat.call(cat,'鱼');

      fun();

    </script>

  </body>

  </html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值