05 # 手写 bind

本文探讨了JavaScript中bind方法的工作原理,包括如何改变函数的this指向以及参数处理。作者提供了两种实现方式,一种是简单版本,另一种是更复杂的原型继承实现,以确保bind后的函数行为一致。
摘要由CSDN通过智能技术生成

bind 干了什么?

  1. 改变 this 指向
  2. 没有让函数执行,返回一个改变 this 指向后的函数

bind 难点在于参数的收集

手写 bind

简单实现如下:

<script>
    Function.prototype.kaimoBind = function (content) {
        // 获取到 bind 里的剩余参数
        let bindArgs = Array.prototype.slice.call(arguments, 1);
        console.log("bindArgs----->", bindArgs);
        // 这里的 this 指向调用 kaimoBind 的 fn
        let that = this;
        function gn() {
            // 拿到 bind 返回函数的参数
            let gnArgs = Array.prototype.slice.call(arguments);
            console.log("gnArgs----->", gnArgs);
            // 改变 fn 的 this 指向
            return that.apply(content, bindArgs.concat(gnArgs));
        }
        return gn;
    };

    function fn(...args) {
        console.log("fn----this----->", this);
        console.log("fn----args----->", args);
        return args.join("");
    }

    let obj = {
        name: "kaimo313"
    };

    let res = fn.bind(obj, "k", "a", "i", "m", "o");
    console.log("res---bind-->", res(3, 1, 3));

    let res2 = fn.kaimoBind(obj, "k", "a", "i", "m", "o");
    console.log("res2---kaimoBind-->", res2(3, 1, 3));
</script>

在这里插入图片描述

复杂一点实现如下:

<script>
    Function.prototype.kaimoBind = function (content) {
        // 获取到 bind 里的剩余参数
        let bindArgs = Array.prototype.slice.call(arguments, 1);
        console.log("bindArgs----->", bindArgs);
        // 这里的 this 指向调用 kaimoBind 的 fn
        let that = this;
        function gn() {
            // 拿到 bind 返回函数的参数
            let gnArgs = Array.prototype.slice.call(arguments);
            console.log("gnArgs----->", gnArgs);
            // 改变 fn 的 this 指向
            return that.apply(content, bindArgs.concat(gnArgs));
        }
        function Mn() {}
        Mn.prototype = this.prototype;
        // gn 继承 Mn
        gn.prototype = new Mn();
        return gn;
    };

    function fn(...args) {
        console.log("fn----this----->", this);
        console.log("fn----args----->", args);
        return args.join("");
    }

    fn.prototype.kaimo = 313;

    let obj = {
        name: "kaimo313"
    };

    let res = fn.bind(obj, "k", "a", "i", "m", "o");
    console.log("res---bind-->", res(3, 1, 3));

    let res2 = fn.kaimoBind(obj, "k", "a", "i", "m", "o");
    console.log("res2---kaimoBind-->", res2(3, 1, 3));

    let res3 = new res2();
    console.log("res3----->", res3.kaimo);
</script>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凯小默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值