implement myCall, myApply, myBind

Show the code directly.

myCall:

1
2
3
4
5
6
7
8
Function.prototype.myCall = function(ctx) {
ctx = ctx || window;
ctx.fn = this;
let args = [...arguments].slice(1);
let result = ctx.fn(...args);
delete ctx.fn;
return result;
}

myApply:

1
2
3
4
5
6
7
8
Function.prototype.myApply = function(ctx) {
ctx = ctx || window;
ctx.fn = this;
let args = arguments[1];
let result = ctx.fn(...args);
delete ctx.fn;
return result;
}

myBind:

1
2
3
4
5
6
7
8
Function.prototype.myBind = function(ctx) {
let that = this;
let args = [...arguments].slice(1);
return function() {//currying
const newArgs = [...arguments];
return that.apply(ctx, args.concat(newArgs));
}
}

Comments