js中 call,apply,bind的区别

   call、apply、bind都是改变this指向的方法

<!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>

</body>

</html>
<script>
    let cat = {
        name: '喵喵'
    }
    let dog = {
        name: '汪汪',
        eat: function (food) {
            console.log(`this指向=》${this.name}, 我喜欢吃${food}`)
        },
        eatMore: function (food1, food2) {
            console.log(`this指向=》${this.name}, 我喜欢吃${food1}和${food2}`)
        }
    }

    // call是函数的方法,可以调用函数
    // call的第一个参数可以改变函数中this的指向
    // call的第二个参数开始的参数是要传入函数的参数
    dog.eat.call(cat)  // this指向=》喵喵, 我喜欢吃undefined
    dog.eat.call(cat, '老鼠')  // this指向=》喵喵, 我喜欢吃老鼠
    dog.eatMore.call(cat, '老鼠', '鱼')  // this指向=》喵喵, 我喜欢吃老鼠和鱼

    // apply和call的区别就是传参不一样,apply的参数列表通过数组传递
    dog.eatMore.apply(cat, ['老鼠', '鱼'])  // this指向=》喵喵, 我喜欢吃老鼠和鱼

    // bind的传参方式和call一样
    // bind和call以及apply的区别在于bind不会调用函数,而是把函数作为返回值,好处就是方便多次调用
    dog.eatMore.bind(cat, '老鼠', '鱼')  // 不执行,bind不会主动调用函数
    let fn = dog.eatMore.bind(cat, '老鼠', '鱼')
    fn() // this指向=》喵喵, 我喜欢吃老鼠和鱼
</script>

 

posted @ 2022-06-17 17:32  我是一名好程序员  阅读(45)  评论(0编辑  收藏  举报