Created
September 12, 2020 12:15
-
-
Save lilywang711/34fa29c73c3b2b51564aee8d9e462d1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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