Function.prototype.call = function (obj, ...args) {
if (typeof this !== 'function') {
throw 'not a function';
}
let fn = Symbol('fn');
obj[fn] = this;
let res = obj[fn](...args);
delete obj[fn];
return res;
}
Function.prototype.apply = function (obj, arr) {
if (typeof this !== 'function') {
throw 'not a function';
}
let fn = Symbol('fn');
obj[fn] = this;
let res = obj[fn](...arr);
delete obj[fn];
return res;
}
Function.prototype.bind = function (obj, ...args) {
if (typeof this !== 'function') {
throw 'not a function';
}
let self = this;
let newFunc = function () {
// arguments是类数组对象,不能直接用slice
self.apply(obj, args.concat(Array.prototype.slice.call(arguments)))
}
return newFunc;
}
手写实现Call Apply Bind
最新推荐文章于 2024-08-25 10:29:19 发布