手写call、apply、bind

100 阅读1分钟

1.call、apply、bind

**相同点:**都可以改变this的指向
不同点:
1.call和apply除了改变了this指向外还执行了函数,bind不会执行函数,会返回一个新的函数;
2.call和apply的传递的参数格式不同,call传递单个参数(例如fn.call(obj,1,2)),apply第二个参数为数组

call

Function.prototype.newCall = function(obj,...args){//把方法添加到构造函数的原型上
	obj = Object(obj) || window;
	obj.fn = this;
    const res = obj.fn(...args);//如果有返回值,将值返回
    delete obj.fn;
    return res;
}   

apply

Function.prototype.newApply = function(obj,arr){//把方法添加到构造函数的原型上
	obj = Object(obj) || window;
	obj.fn = this;
    const res = obj.fn(arr);//如果有返回值,将值返回
    delete obj.fn;
    return res;
}

bind

Function.prototype.newBind = function(obj){//把方法添加到构造函数的原型上
	obj = Object(obj) || window;
	const me = this;
    let args = Array.prototype.slice.call(arguments, 1);//从第二个参数截取至最后并转换为数组
    return function () {
    	let bindArgs = Array.prototype.slice.call(arguments);//将参数转换为数组
    	return me.apply(obj, args.concat(bindArgs));
    }
    return res;
}

>>>前端学习之路<<<