十二、手写call,apply和bind

61 阅读1分钟

原理: 就函数在特定作用域中执行,也就是在将调用call的函数变成ctx的某个属性上的方法。

      Function.prototype.mycall = function(ctx,...args) {
            ctx = ctx || window
            ctx._prop = this
            return ctx._prop(...args)
        }
        Function.prototype.myapply = function(ctx, ary) {
            ctx = ctx || window
            ctx._prop = this
            return ctx._prop(...ary)
        }
        Function.prototype.mybind = function(ctx, ...args) {
            ctx = ctx || window
            const _fn = this
            return function() {
                return _fn.call(ctx, ...args)
            }
        }
        const obj = {
            a: 10,
            b: 10
        }

        var a = 1
        var b = 2

        function fn(c, d) {
            return this.a + this.b + c + d
        }
        const res = fn(3, 4)
        // console.log(res) // 10  

        const resCall = fn.call(obj, 3, 4)
        // console.log('call', resCall) // 27

        const resMyCall = fn.mycall(obj, 3, 4)
        // console.log('mycall', resMyCall) // 27

        const resMyApply = fn.myapply(obj, [3,4])
        // console.log('myapply', resMyApply) // 27

        const resApply = fn.apply(obj, [3,4])
        // console.log('apply', resApply) // 27

        const newFn = fn.bind(obj, 3,4)
        // console.log(newFn())
        const newMyFn = fn.mybind(obj, 3,4)
        console.log(newMyFn()) // 27