最近公司被收购了,很不辛被迫开始找工作:
所以记录一下面试题的重难点,加深一下记忆。
开始正题
手写apply,call,bind函数?
这道题其实理清楚apply
,call
,bind
的特点就行了。首先apply
,call
,bind
都是强制绑定this
,而apply
和call
都是立即执行,只有bind
是返回一个函数,所以可以将apply
和call
放在一起分析。
apply和call
apply
和call
唯一的区别在于传递参数的方式,apply是传递数组
,而call是剩余参数
(function(...arg){...}
)的形式。而this
强绑定的实现,可以在绑定对象
的实例上赋值执行对象
的方式实现。代码如下:
call
Function.prototype._call = function (context, ...args) {
let result = null;
context = Object(context) || window;
context.fn = this;
result = context.fn(...args);
Reflect.deleteProperty(context, 'fn');
return result;
};
function a (a, b) {
}
a._call({}, 1, 2, 3);
apply
apply
和call
区别不大,只是转变下传参方式,使用数组即可:
Function.prototype._apply = function (context, args = []) {
let result = null;
context = Object(context) || window;
context.fn = this;
result = context.fn(...args);
Reflect.deleteProperty(context, 'fn');
return result;
};
bind
bind
函数和其它两个相比是比较复杂的,因为它不是立即执行
,所以可能发生new
的情况,当然发生new
的情况我们可以使用es6
的new.target
来判断:
Function.prototype._bind = function (context, ...args) {
const _this = this;
context = Object(context) || window;
context.fn = this;
return function F(...otherArgs) {
let result = null;
if (new.target) {
return new _this(...args.concat(otherArgs));
} else {
result = context.fn(...args.concat(otherArgs));
}
Reflect.deleteProperty(context, 'fn');
return result;
};