js 手写call

188 阅读1分钟

js 手写call

    // call的实现原理
    Function.prototype.mycall = function (ctx) {

        ctx = ctx || window // 有就用ctx 没有就用window
        ctx._F = this; // a._F = this (添加属性) ,this===b (this指向b)
        let arg = [...arguments].slice(1) // 截取参数
        let res = ctx._F(...arg); // 
        return res
    }

    var a = {
        name: 'cherry',
        fn: function (a, b) {
            console.log(this);
            console.log(a + b);
        }
    }
    var b = a.fn
    b.mycall(a, 33, 44)