欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Javascript中bind,call,apply模拟实现

程序员文章站 2022-07-14 14:27:40
...
Function.prototype.bindFake = function(context) {
    let fn = this;
    let arr = Array.prototype.slice.call(arguments, 1);
    return function() {
        let innerArgs = Array.prototype.slice.call(arguments);
        let args = arr.concat(innerArgs);
        fn.apply(context, args);
    }
}

Function.prototype.callFake = function(context) {
    let context = context || window;
    context.fn = this;
    let arr = [];
    let result;
    for(let i = 1; i < arguments.length; i++) {
        arr.push('arguments[' + i + ']');
    }
    if (arr) {
        result = eval('context.fn(' + arr + ')');
    } else {
        result = context.fn();
    }
    delete context.fn;
    return result;
}

Function.prototype.applyFake = function(context, arr) {
    let context = context || window;
    context.fn = this;
    let result;
    if (arr) {
        let args = [];
        for(let i = 0; i< arr.length; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')');
    } else {
        result = context.fn();
    }
    
    delete context.fn;
    return result;
}