call()和apply()方法

一、这两个方法的作用是什么?

这两个方法都会以指定的 this 值来调用函数,即会设置调用函数时函数体内 this 对象的值。

二、apply()

apply() 方法接收两个参数:函数内 this 的值和一个参数数组。第二个参数可以是 Array 的实例,但也可以是 arguments 对象。

示例:传入arguments 对象

(
    function testApplyArguments() {
        function sum(num1,num2) {
            return num1+num2;
        }
        function callsum1(num1,num2) {
            console.log(this);
            console.log("testApplyArguments");
            return sum.apply(this,arguments);
        }
        console.log(callsum1(10,10));
    }
)();

示例:传入Array对象

(
    function testApplyArray() {
        function sum(num1,num2) {
            return num1+num2;
        }
        function callsum1(num1,num2) {
            console.log(this);
            console.log("testApplyArray");
            return sum.apply(this,[num1,num2]);
        }
        console.log(callsum1(10,10));
    }
)();

三、call()

示例:逐个传递参数

(function testCall() {
    function sum(num1,num2) {
        return num1+num2;
    }
    function callsum1(num1,num2) {
        console.log(this);
        console.log("testCall");
        return sum.call(this,num1,num2);
    }
    console.log(callsum1(10,10));
})();

这里的 callSum() 函数必须逐个地把参数传给 call() 方法。

四、call和apply的真正意图

apply() 和 call() 真正强大的地方并不是给函数传参,而是控制函数调用上下文即函数体内 this值的能力。

(function testRealmean() {
    global.color = 'red';

    let mycolor = {
        color : 'pink'
    }
    
    function showColor() {
        console.log(this.color);
    }

    showColor();

    showColor.call(mycolor);

})();

五、bind()

bind() 方法会创建一个新的函数实例,其 this 值会被绑定到传给 bind() 的对象。

(function testBind() {
    global.color = 'red';

    let mycolor = {
        color : 'pink'
    }
    
    function showColor() {
        console.log(this.color);
    }

    let showColorBind = showColor.bind(mycolor);

    showColorBind();
})();

bind()会返回一个绑定了this的新函数,即使在全局作用域下调用,他的this值也不是global,而是bind()指定的对象参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值