chenshuhong / fullstack

我的全栈路线思维导图以及日常知识记录
MIT License
0 stars 0 forks source link

JavaScript深入之call,apply,bind的模拟实现 #1

Open chenshuhong opened 4 years ago

chenshuhong commented 4 years ago

参考 JavaScript深入之call,apply的模拟实现 JavaScript深入之bind的模拟实现

Function.prototype.apply和Function.prototype.call 的作用是一样的,区别在于传入参数的不同; 第一个参数都是,指定函数体内this的指向,this 参数可以传 null,当为 null 的时候,视为指向 window 第二个参数开始不同,apply是传入带下标的集合,数组或者类数组,apply把它传给函数作为参数,call从第二个开始传入的参数是不固定的,都会传给函数作为参数。 call比apply的性能要好,平常可以多用call,尤其是es6 引入了 Spread operator (延展操作符) 后,即使参数是数组,可以使用 call

chenshuhong commented 4 years ago
Function.prototype.call2 = function (context) {
    var context = context || window;
    context.fn = this;

    var args = [];
    for(var i = 1, len = arguments.length; i < len; i++) {
        args.push('arguments[' + i + ']');
    }

    var result = eval('context.fn(' + args +')');

    delete context.fn
    return result;
}
chenshuhong commented 4 years ago
Function.prototype.apply = function (context, arr) {
    var context = Object(context) || window;
    context.fn = this;

    var result;
    if (!arr) {
        result = context.fn();
    }
    else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')')
    }

    delete context.fn
    return result;
}
chenshuhong commented 4 years ago