js实现call,apply和bind

call:

Function.prototype.$call = function(context) {
    var context = context || window;
    context.fn = this;
    var args = Array.from(arguments).slice(1)
    context.fn(...args)
    delete context.fn;
}

apply:

Function.prototype.$apply = function(context) {
    var context = context || window;
    context.fn = this;
    var args = Array.from(arguments[1])
    context.fn(...args)
    delete context.fn;
}

bind:

Function.prototype.$apply = function(context) {
    var context = context || window;
    context.__proto__.fn = this;
    var args = Array.from(arguments).slice(1)
    return function(){
        var args2 = Array.from(arguments)
        context.fn(...args,...args2)
        delete context.__proto__.fn
    }
}

猜你喜欢

转载自www.cnblogs.com/AwenJS/p/12695283.html