JavaScript:模拟实现call、apply、bind

call实现

call的作用

call() 方法在使用一个指定的 this 值和若干个指定的参数值的前提下调用某个函数或方法。

代码实现

直接上代码:

Function.prototype.call2 = function (context) {
    var context = context || window; //若context是null,最后this指向window
    context.fn = this; // 给这个上下文添加一个fn对象指向调用的的函数

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

    var result = eval('context.fn(' + args +')'); // 这里 args 会自动调用 Array.toString() 这个方法

    delete context.fn //添加了fn之后还要删除这个属性
    return result; // 函数一般都有返回值
}

测试

var foo = {
    value: 1
};

function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}

bar.call2(foo, 'kevin', 18); 
// kevin
// 18
// 1

eval使用

apply实现

与call类似,注意apply的第二个参数是一个数组

代码

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;
}

bind

bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )

Function.prototype.bind2 = function (context) {

    if (typeof this !== "function") {
      throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fNOP = function () {};

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
    }

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}
}

参考资料:
1.JavaScript深入之call和apply的模拟实现
2.JavaScript深入之bind的模拟实现

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/XF-eng/p/15028900.html