23. js - インタビュー - call()apply()bind()

<body>
    <button>我是按钮</button>
</body>

</html>

<script>

    // call  apply  bind 都可以改变this指向

    function fn(a, b) {
        const title = 'ts';
        console.log(this);
        console.log(this.title);
        return a + b;
    }

    const obj = {
        title: 'vite'
    }

    // 一、call()
    // call()的作用:
    // 1、会直接调用函数
    fn.call();
    // 2、会改变this指向
    // 参数1:this指向
    // 剩余参数:传给函数的参数
    const result1 = fn.call(obj, 1, 2);
    console.log(result1); // 3

    // call()的应用场景:检测数据类型
    const arr = [1, 2, 3];
    const obj1 = { name: 1 };
    console.log(arr.toString()); // 1,2,3
    console.log(obj1.toString()); // [object Object]
    // 使用call()方法改变toString()方法的this指向为arr,得到[object Array]
    console.log(Object.prototype.toString.call(arr)); // [object Array]


    // 二、apply()
    // apply()的作用:
    // 1、会直接调用函数
    fn.apply();
    // 2、会改变this指向
    // 参数1:this指向
    // 参数2:传给函数的参数,必须是个数组
    const result2 = fn.apply(obj, [1, 2]);
    console.log(result2); // 3

    // apply()的应用场景:求数组的最大值
    const arr1 = [1, 2, 3, 4];
    console.log(Math.max.apply(null, arr1)); // 4
    // 等价于es6用展开运算符解决
    console.log(Math.max(...arr1)); // 4


    // 三、bind()
    // bind()的作用
    // 1、不会直接调用函数
    // 2、会改变this指向
    // 3、会返回一个新函数,新函数里的this指向参数1
    // 参数1:this指向
    // 剩余参数:传给函数的参数
    const result3 = fn.bind(obj, 3, 4);
    console.log('result3--->', result3()); // result3---> 7

    // bind()应用场景:需要改变函数的this指向,又不想调用函数,比如修改延时器的函数的this指向
    document.querySelector('button').addEventListener('click', function () {
        
        setTimeout(function () {
            console.log(this); // <button>我是按钮</button>
            this.style.color = "red";
        }.bind(this), 3000);

        // 等价于es6用箭头函数解决
        setTimeout(() => {
            this.style.color = "red";
        }, 3000);
    })

</script>

Guess you like

Origin blog.csdn.net/EchoLiner/article/details/131067989