call 和 apply 的模拟实现—— JavaScript

call

call 方法在使用一个指定的 this 和若干个参数的情况下调用某个函数或方法。例如:

<script>
    let foo = {
        value: "foo"
    };

    function pri() {
        console.log(this.value);
    }
    pri.call(foo);    //foo
</script>

模拟实现要注意以下:

(1)call 改变了 pri 的 this 的指向,指向到 foo

(2)pri 函数执行了

(3)call 函数可以传递参数

(4)传入的 this 可以为 null,当 this 为 null 的时候,默认指向 window。

(5)函数是可以有返回值的

<script>
    let foo = {
        value: "foo"
    };

    function pri(name, age) {
        console.log(this.value);
        return {
            value: this.value,
            name: name,
            age: age
        }
    }

    Function.prototype.change = function(context) {
        context = context == null? window : context;
        //如果传入的 this 为 null,则指向 window
        context.fn = this;
        //获取调用这个函数的函数
        let arr = [];
        for (let i = 1; i < arguments.length; i++) {
            arr.push(arguments[i]);
        }
        //获取参数
        //第一个参数为传入的 this,所以从第二个开始获取
        let result = context.fn(...arr);
        //传入参数并执行该函数
        //(...)可以将可迭代对象拆分,并将迭代返回的每个值单独传入
        delete context.fn;
        //delete 操作符用于删除对象的某个属性
        return result;
        //返回结果
    }
</script>

效果:


apply

类似于 call,不过 apply 方法第二个参数为一个数组。

<script>
    let foo = {
        value: "foo"
    };

    function pri(name, age) {
        console.log(this.value);
        return {
            value: this.value,
            name: name,
            age: age
        }
    }

    Function.prototype.change = function(context, arr) {
        context = context == null? window : context;
        //如果传入的 this 为 null,则指向 window
        context.fn = this;
        //获取调用这个函数的函数
        let result;
        //返回值
        if (arr == null) {
            result = context.fn();
        } else {
            result = context.fn(...arr);
        }
        //传入参数并执行该函数
        //(...)可以将可迭代对象拆分,并将迭代返回的每个值单独传入
        delete context.fn;
        //delete 操作符用于删除对象的某个属性
        return result;
        //返回结果
    }
</script>

效果:


火锅真好吃!

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值