关于javascript:关于apply和call

3次阅读

共计 946 个字符,预计需要花费 3 分钟才能阅读完成。

apply 和 call 两个办法都能扭转函数外面 this 的指向,扭转后的函数 this 指向办法内的第一个参数。apply 和 call 的次要区别在于,apply 前面向函数传递参数是借用的数组的模式,而 call 则应用逗号将参数分隔开即可。

示例:

<!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>Document</title>
</head>
<body>
  <script>
    //call 的办法会把函数的 this 指向 指向函数的第一个参数,call 传参的形式是逗号分隔开
    const sm = {
      name: '蜘蛛侠',
      age: 25,
      dreams(truthName ,truthAge){
        this.name = truthName
        this.age = truthAge
      }
    }
    sm.dreams('托比', 23)
    console.log(`sm 的 `,sm);

    const em = {
      name: '钢铁侠',
      age: 25
    }
    sm.dreams.call(zjh , '小罗伯特唐尼' , 88)
    console.log(`em 的 `,em);


    //apply 的办法也会把 this 指向 指向函数的第一个参数,和 call 不同的是,apply 的参数是以数组的形式传递的
    const today = {
      weather: '晴天',
      date: '5 月 9 号',
      correct(weather,date){
        this.weather = weather
        this.date = date
      }
    }

    today.correct('暴雨','5 月 10 号')
    console.log('today', today);
    const tomorrow = {
      weather: '小雨',
      date: '不晓得'
    }
    today.correct.apply(tomorrow, ['大晴天', '5 月中旬'])
    console.log('tomorrow' ,tomorrow);


  </script>
</body>
</html>

图示:

欢送指错!

正文完
 0