technology-blog icon indicating copy to clipboard operation
technology-blog copied to clipboard

第 7 题:手写代码,简单实现apply

Open airuikun opened this issue 6 years ago • 3 comments

Function.prototype.apply2 = function(context, arr) {
    var context = context || window; //因为传进来的context有可能是null
    context.fn = this;
    var args = [];
    var params = arr || [];
    for (var i = 0; i < params.length; i++) {
        args.push("params[" + i + "]"); //不这么做的话 字符串的引号会被自动去掉 变成了变量 导致报错
    }
    args = args.join(",");

    var result = eval("context.fn(" + args + ")"); //相当于执行了context.fn(arguments[1], arguments[2]);

    delete context.fn;
    return result; //因为有可能this函数会有返回值return
}

airuikun avatar Apr 08 '19 08:04 airuikun

ES 6版本

Function.prototype.apply2 = function(context, arr) {
    let context = context || window; // 因为传进来的context有可能是null
    context.fn = this;
    arr = arr || [];
    const result = context.fn(...arr); // 相当于执行了context.fn(arguments[1], arguments[2]);
    delete context.fn;
    return result; // 因为有可能this函数会有返回值return
}

nelsonkuang avatar Apr 17 '19 03:04 nelsonkuang

参数中带 context ,再用 let 声明一遍会报错的

2fps avatar Aug 10 '19 14:08 2fps

ES 6版本

Function.prototype.apply2 = function(context, arr) {
    let context = context || window; // 因为传进来的context有可能是null
    context.fn = this;
    arr = arr || [];
    const result = context.fn(...arr); // 相当于执行了context.fn(arguments[1], arguments[2]);
    delete context.fn;
    return result; // 因为有可能this函数会有返回值return
}

既然都已经用ES6了,就再彻底点

Function.prototype.myApply = function(context = window, args = []) {
    context.fn = this;
    const result = context.fn.call(context, ...args);
    delete context.fn;
    return result;
}

wilsonwangdev avatar Aug 04 '21 13:08 wilsonwangdev