Function.prototype._bind = function(...args) {
if (typeof this !== 'function') return;
const _this = args.shift();
const self = this;
return function() {
return self.apply(_this, args);
};
};
// 测试代码
function fn() {
console.log(this); // { x:100 }
}
let say = fn._bind({ x: 100 }, 1, 2, 3);
say();
Function.prototype._call = function (ctx, ...args) {
const obj = ctx == undefined ? window : Object(ctx);
obj.fn = this;
const result = obj.fn(...args);
delete obj.fn;
return result;
};
fn._call({ x: 100 }, 1, 2);
Function.prototype._apply = function (ctx, array = []) {
const obj = ctx == undefined ? window : Object(ctx);
obj.fn = this;
const result = obj.fn(...array);
delete obj.fn;
return result;
};
fn.apply({ x: 100 }, [1, 2]);