call、apply、bind的区别?(面试题-JavaScript部分)

共同点:

                可以改变this指向

                语法: 函数.call()、函数.apply()、函数.bind()

不同点:

                1. call、apply可以立即执行

                    bind不会立即执行,因为bind返回的是一个函数需要加入()执行。


                2. 参数不同:

                                apply第二个参数是数组

                                call和bind有多个参数需要挨个写。

                3.场景:

1. 用apply的情况
        var arr1 = [1,2,4,5,7,3,321];
        console.log( Math.max.apply(null,arr1) )

2. 用bind的情况
        var btn = document.getElementById('btn');
        var h1s = document.getElementById('h1s');
        btn.onclick = function(){
               console.log( this.id );
        }.bind(h1s)

例子:

        · 原本的情况:

        var a = '你好';
        function fun(){
            console.log( this ,this.a )
        }
        fun();      //调用fun函数

                输出结果:

         · 用call改变this指向:

var a = '你好';
var b = {a:'这是b对象内的a'}
function fun(){
       console.log( this ,this.a )
}
        
fun.call(b); //立即执行
fun();      //调用fun函数
fun.apply(b); //立即执行
console.log( fun.bind(b) );  //输出结果是一个函数
fun.bind(b)();               //所以bind不是立即执行,需要加()后才会执行

                输出结果:

         · 参数不同:

        var a = '你好';
        var b = {a:'这是b对象内的a'}
        function fun(name,age){
            this.name = name;
            this.age = age;
            console.log( this ,this.a );
        }
        fun.call(b,'小马',18);
        fun.bind(b,'Kiangkiang',20)();

                输出结果:

                · 使用场景:

<body>
    <button id="btn">按一下改变this指向,指向id为h1s</button>
    <h1 id="h1s">222</h1>
    <script>
        
       // 1. 用apply的情况
        var arr1 = [1,2,4,5,7,3,321];
        console.log( Math.max.apply(null,arr1) )

       // 2. 用bind的情况
        var btn = document.getElementById('btn');
        var h1s = document.getElementById('h1s');
        btn.onclick = function(){
            console.log( this.id );
        }.bind(h1s)
    </script>
</body>

                 输出结果:

猜你喜欢

转载自blog.csdn.net/weixin_54614831/article/details/126442668