练习部分手写题(call/apply/bind)

做个总结贴。

  1. call/apply/bind
        Function.prototype.apply = function (obj, args) {
            // 参数处理
            if (!obj) obj = window;
            else obj = Object(obj);
            args = Array.from(args);
            // 绑定this
            const testFn = Symbol('testFn');
            obj[testFn] = this;
            let res = obj[testFn](...args);
            delete obj[testFn];
            return res;
        }

        Function.prototype.call = function (obj, ...args) {
            // 参数处理 
            if (!obj) obj = window;
            else obj = Object(obj);
            // 绑定this
            const testFn = Symbol('testFn');
            obj[testFn] = this;
            let res = obj[testFn](...args);
            delete obj[testFn];
            return res;
        }

        Function.prototype.bind = function (obj) {
            // 参数处理
            if (!obj) obj = window;
            else obj = Object(obj);

            let that = this; // 保存函数
            // 通过闭包,进行临时绑定
            return function (...args) {
                const testFn = Symbol('testFn');
                obj[testFn] = that;
                let res = obj[testFn](...args);
                delete obj[testFn];
                return res;
            }
        }

        // test   call/apply/bind
        function fn(a) {
            console.log(a + this.b);
        }

        fn.apply({ b: 3 }, [5]);
        fn.call({ b: 3 }, 4);

        let add = fn.bind({ b: 9 });
        add(8);
        add(9)

2.new

        function mynew(func, args) {
            // 构造函数 参数数组
            if (func && typeof func !== 'function') {
                return {}; // 或者 throw error
            }

            let child = {};
            child.__proto__ = func.prototype;
            func.apply(child, args);
            return child;
        }

        function A(a = -5) {
            this.a = a;
            this.b = 5;
        }

        A.prototype.add = function () {
            console.log(this.a + this.b)
        }

        let a = mynew(A, [5]);
        a.add()

        let b = mynew(A);
        b.add()

补充部分
关于bind的参数添加可以通过闭包实现,类似柯里化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值