call和apply的实现!

2019-08-22 22:03:48 浏览数 (1)

apply的具体实现

代码语言:javascript复制
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
}
复制代码

call的具体实现

代码语言:javascript复制
Function.prototype.call = 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
}

复制代码

0 人点赞