call,apply,bind

93 阅读1分钟
Function.prototype.call = function(context){
    var context = context || window
    context.fn = this
    var args = []
    var len = arguments.length
    for(var i = 1; i < len; i++){
        args.push('arguments[' + i +']')
    }
    var res = eval('context.fn(' + args + ')')
    delete context.fn
    return res
}
Function.prototype.apply = function (context, arr) {
    var context = 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;
}
Function.prototype.bind = function (context){
    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
}