概述
- 常见面试题,手动实现call、apply、bind
- 本文将在Function原型上扩展方法
_call
、_apply
、_bind
模拟实现call、apply、bind
一、模拟call实现_call
在Function原型上扩展方法_call,模拟call的实现
Function.prototype._call = function (_this, ...args) {
const fn = this;
_this = _this !== undefined && _this !== null ? Object(_this) : window;
_this.fn = fn;
const res = _this.fn(...args);
delete _this.fn;
return res;
};
二、模拟apply实现_apply
在Function原型上扩展方法_apply,模拟apply的实现
Function.prototype._apply = function (_this, arr) {
const fn = this;
_this = _this !== undefined && _this !== null ? Object(_this) : window;
_this.fn = fn;
const res = _this.fn(...(arr || []));
delete _this.fn;
return res;
};
三、模拟bind 实现_bind
在Function原型上扩展方法_bind ,模拟bind 的实现
Function.prototype._bind = function (_this, ...args1) {
const fn = this;
_this = _this !== undefined && _this !== null ? Object(_this) : window;
return function (...args2) {
_this.fn = fn;
const res = _this.fn(...[...args1, ...args2]);
delete _this.fn;
return res;
};
};