call
function fn1() {
console.log(this);
}
function fn2() {
console.log(100);
}
Function.prototype.call = function(context, ...args) {
context = context ? Object(context) : global;
context.fn = this;
let result = context.fn(...args);
delete context.fn;
return result;
}
fn1.call(1);
fn1.call.call.call.call.call(fn2);
apply
Function.prototype.apply = function(context, arrArgs) {
context = context ? Object(context) : global;
context.fn = this;
let result = context.fn(...arrArgs);
delete context.fn;
return result;
}
function fn3(a, b) {
console.log(this, a, b);
}
fn3.apply(1, [2, 3]);
bind
Function.prototype.bind = function(context) {
let self = this;
return function(...args) {
return self.call(context, ...args);
}
}
function fn4(a, b) {
console.log(this, a, b);
}
fn4.bind(1)(2, 3);
function fn5() {
console.log(this);
}
fn5.bind(1).bind(2)();