apply() call() bind()作用与区别

本文深入探讨了JavaScript中apply(), call(), bind()方法的区别及应用,解析如何通过这些方法改变函数执行上下文,即改变函数体内this的指向,实现多重继承。通过具体代码示例,清晰展示了不同场景下三种方法的使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

apply()、call()、bind()调用对象的一个方法,用另一个对象代替当前对象;改变函数执行的上下文,换句话说就是改变函数体内部的this的指向,实现(多重)继承

区别:

bind()是返回的是执行上下文被改变的函数且不会立即执行,call()、apply()直接执行该函数;

call()的传参是 call(this,param1,param2…),参数必须直接传给函数

apply()的传参是 apply(this,[argArray]);

bind()的传参是bind(this,param1,param2…);

第一个参数是指定的对象,这个对象就是该函数的执行上下文

call()和apply()如果第一个参数是null或者undefine那么this的指向就是全局变量,在浏览器里就是window对象

代码示例;

// apply()
    let obj = {};
    // 不需要参数的情况
    function test() {
        console.log(this === window);
        console.log(this === obj);
    }
    test(); // true	false
    test.apply(obj); //false	true

    // 需要传参的
    let obj = {
        name: '飞哥'
    };
    function test(name) {
        this.name = name;
        console.log(window.name);
        console.log(obj.name);
    }

    test("高飞"); // 高飞	飞哥
    test.apply(obj, ['高飞']); // 高飞	高飞


    // call() 

    // 不需要参数的情况
    let obj = {};
    function test() {
        console.log(this === window);
        console.log(this === obj);
    }

    test(); // true	false
    test.apply(obj); //false	true

    // 需要传参的
    let obj = {
        name: '飞哥'
    };

    function test(name) {
        this.name = name;
        console.log(window.name);
        console.log(obj.name);
    }

    test("高飞"); // 高飞	飞哥
    test.call(obj, '高飞'); // 高飞	高飞


    // bind()

    // 不需要参数的情况
    let obj = {};
    function test() {
        console.log(this === window);
        console.log(this === obj);
    }

    test(); // true	false
    test.bind(obj)(); //false	true

    // 需要传参的
    let obj = {
        name: '飞哥'
    };

    function test(name) {
        this.name = name;
        console.log(window.name);
        console.log(obj.name);
    }

    test("高飞"); // 高飞	飞哥
    test.bind(obj, '高飞')(); // 高飞	高飞

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值