Skip to content

Instantly share code, notes, and snippets.

@lilywang711
Created September 12, 2020 12:15
Show Gist options
  • Save lilywang711/34fa29c73c3b2b51564aee8d9e462d1b to your computer and use it in GitHub Desktop.
Save lilywang711/34fa29c73c3b2b51564aee8d9e462d1b to your computer and use it in GitHub Desktop.
var type = "window";
const obj = {
type: "obj",
foo(a, b) {
console.log("this.type", this.type, a, b);
}
};
Function.prototype.customCall = function (context, ...restArgs) {
context = context == null ? window : context;
context.func = this;
return context.func(...restArgs);
};
obj.foo.customCall(window, 1, 2);
// obj.foo.call(window, 1, 2);
Function.prototype.customApply = function (context, restArgs) {
context = context == null ? window : context;
context.func = this;
return context.func(...restArgs);
};
// obj.foo.customApply(window, [1, 2]);
// obj.foo.apply(window, [1, 2]);
Function.prototype.customBind = function (context) {
context = context == null ? window : context;
context.func = this;
return function anonymous(...returnArgs) {
return context.func(...returnArgs);
};
// or
// const _this = this
// return function anonymous (...returnArgs) {
// return _this.call(context, ...returnArgs)
// };
};
const bindFunc = obj.foo.customBind(window);
// bindFunc(1, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment