• 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>
  • 相关阅读:
    OC中extern,static,const的用法
    pod install 报错
    设置Image渲染模式使用TintColor
    VLC 用到的那些 YUV 格式
    base64编码原理
    scp 拷贝文件时报错
    linux 恢复误删文件
    hadoop 集群安装(Cloudera CDH方式)
    记录自己需要读的几本书
    求解最长回文子串
  • 原文地址:https://www.cnblogs.com/wangqi2019/p/16386547.html
Copyright © 2020-2023  润新知