关于JS call ,apply, bind之间的用法以及区别

call, apply, bind 主要实现的功能是改变this的指向.

在正常情况下 console.log(this)  输出的内容是 window 对象

 

第一个call函数

复制代码
 <script>
        // 改变函数内this指向  js提供了三种方法  call()  apply()  bind()
        var o = {
            name: 'andy'
        }

        function fn(a, b){
            console.log(this);
            console.log(a + b);
        };

        fn.call(o, 1, 2);

        // call第一个可以调用函数 第二个可以改变函数内的this 指向

        function Father(uname, age, sex){
            this.uname = uname;
            this.age = age;
            this.sex = sex;
        }

        function Son(uname, age, sex){
            Father.call(this, uname, age, sex);
        }

        var son = new Son('刘德华', 18, '男');
        console.log(son);
    </script>
复制代码

 

第二个 apply()   与call的区别主要是 apply后面加的是类数组

复制代码
 <script>
        // apply()应用 运用的意思

        var o = {
            name: 'andy'
        };

        function fn(arr) {
            console.log(this);
            console.log(arr); // pink
        };

        fn.apply(o, ['pink']);

        var arr = [1, 66, 3, 99, 4];
        var arr1 = ['red', 'pink'];

        // The Math.max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.
        var max = Math.max.apply(Math, arr);
        var min = Math.min.apply(Math, arr);

        console.log(max, min);
    </script>        
复制代码

MDN有更加详细的内容https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply  

 

第三个 bind() 可看作绑定函数

复制代码
 // bind() 绑定 捆绑的意思
        var o = {
            name: 'andy'
        };

        function fn(a, b) {
            console.log(this);
            console.log(a + b);
        }

        var f = fn.bind(o, 1, 2)
        fn();

        var btn1 = document.querySelector('button');
        btn1.onclick = function() {
            this.disabled = true; // 这个this 指向的是 btn 这个按钮
            // var that = this;
            setTimeout(function() {
                // that.disabled = false; // 定时器函数里面的this 指向的是window
                this.disabled = false; // 此时定时器函数里面的this 指向的是btn
            }.bind(this), 3000); // 这个this 指向的是btn 这个对象
        }

        //  bind改变this指向后不会调用函数
复制代码

 

posted @   一杯咖啡钱  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示