最近公司被收购了,很不辛被迫开始找工作:
所以记录一下面试题的重难点,加深一下记忆。
开始正题
手写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;
};