JavaScript笔记:call(), apply()

call, apply

  • call()
  • apply()

改变this指向,传参列表不同

call()

//源码
Function.prototype.myCall = function (){
	var obj = arguments[0] || window;
	var args = [];	
	for(var i = 1, len = arguments.length; i < len; i++){
		args.push('arguments['+i+']');
	}
	console.log(args.join(','));
	obj.fn = this;
	eval('obj.fn('+args.join(',')+')');
	delete obj.fn;
}

apply()

//源码
Function.prototype.myApply = function (obj, arr){
	var obj = obj || window;
	obj.fn = this;
	var args = [];
	if(!arr){
		var result = obj.fn();
		delete obj.fn;
		return result;
	}else{
		for(var i = 0, len = arr.length; i < len; i++){
			args.push('arr['+ i +']');
		}
		eval('obj.fn('+args.join(',')+')');
		delete obj.fn;
	}			
}

你可能感兴趣的:(JavaScript笔记:call(), apply())