apply 和 call的模拟实现

该博客主要围绕apply和call的模拟实现展开,虽内容仅给出转载链接,但可推测重点在于介绍如何模拟实现这两个方法,这在JavaScript编程中是重要的技术点,能帮助开发者更好地理解函数调用机制。

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

// call的作用,改变this的指向
function add(c, d) {
    return this.a + this.b + c + d
}
const obj = {
    a: 1,
    b: 2
}
console.log(add.call(obj, 3, 4))

// 原本add的this指向window 但是现在指向了obj这个对象

const obj2 = {
    a: 1,
    b: 2,
    add2: function (c, d) {
        return this.a + this.b + c + d
    }
}

obj2.add2(3, 4)

// 这段代码和上面得到的结果是一样的

// call主要是改变了this的指向,所以通过上面代码的比较 我们可以三部分
// 1.obj中添加add2这个属性 2.执行add2  3.删掉add2(不能改变原对象的属性)


Function.prototype.callMock = function (context) {
    // 防止context为null
    var content = context || window
    // this调用对象 function add
    content.fn = this
    var args = []
    for (var i = 1, len = arguments.length ; i < len; i++) {
        args.push('arguments[' + i + ']');
    }
    var result = eval('content.fn('+args+')');
    delete content.fn;
    return result;
}
add.callMock(obj, 3, 4)

// apply的作用,改变this的指向
function add(c, d) {
    return this.a + this.b + c + d
}
const obj = {
    a: 1,
    b: 2
}
console.log(add.apply(obj, [3, 4]))
Function.prototype.myApply = function (context, arr) {
    var context = Object(context) || window;
    context.fn = this;

    var result;
    if (!arr) {
        result = context.fn();
    }
    else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')')
    }

    delete context.fn
    return result;
}
console.log(add.myApply(obj))
复制代码

转载于:https://juejin.im/post/5d073d1f51882548ac439c60

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值