手写call、apply、bind函数

callapplybind三者均能改变当前this指向
三者的区别:

  • 三者的第一个参数均为新的this指向
  • 第二个参数:callbind为参数列表,apply为参数数组
  • 只有bind返回一个函数

手写实现call函数

Function.prototype.TestCall = function(thisArg,arg){
	//获取要执行的函数
	let fn = this;
	//转换新this指向的类型
	thisArg = (thisArg !== null && thisArg !==undefiend) ? Object(thisArg) : window;
	thisArg.fn = fn;
	//将函数执行的结果保存
	let result = thisArg.fn(...arg);
	//删除
	delete thisArg.fn;
	//返回函数执行的结果
	return result; 
}

手写实现apply函数

Function.prototype.TestApply = function(thisArg, arrArg){
	let fn = this;
	thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window;
	thisArg.fn = fn;
	//arrArg = arrArg ? arrArg : [];
	arrArg = arrArg || [];
	let result = thisArg.fn(...arrArg);
	delete thisArg.fn;
	return result;
}

手写实现bind函数

Function.prototype.TestBind = function(thisArg, ...argArr){
	let fn = this;
	thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window;
	function proxyFn (...args){
		let finalArr = [...argArr, ...args];
		thisArg.fn = fn;
		let result = thisArg.fn(...finalArr);
		delete thisArg.fn;
		return result;	
	}
	return proxyFn;
}