New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【Q031】js 中如何实现 bind #32
Comments
最简单的 Function.prototype.fakeBind = function(obj, ...args) {
return (...rest) => this.call(obj, ...args, ...rest)
} 测试一下 function f (arg) {
console.log(this.a, arg)
}
// output: 3, 4
f.bind({ a: 3 })(4)
// output: 3, 4
f.fakeBind({ a: 3 })(4) |
那我再抄一个加强版吧嘻嘻
|
This was referenced Jul 30, 2021
Function.prototype.fakeBind = function (target, ...args) {
return (...rest) => this.apply(target, args.concat(rest).slice(0, this.length));
}; |
bind 优化版本:考虑 bind 后返回的函数作为构造函数被 new Function.prototype.bind = function(context, ...args) {
const self = this;
const fn = function(...newArgs) {
self.apply(this instanceof fn ? this : context, args.concat(newArgs));
};
fn.prototype = Object.create(this.prototype);
return fn;
}; |
Function.prototype.myBind = function (ctx) {
ctx ??= globalThis
ctx = Object(ctx)
const self = this
const args = [...arguments].slice(1)
function bound() {
self.call(new.target ? this : ctx, ...args)
}
bound.prototype = self.prototype
return bound
} |
Function.prototype._bind(obj,...args){
obj.fn = this
return function(...args){
const r = obj.fn(...args)
delete obj.fn
return r
}
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
提供以下测试用例,注意第二条测试用例,因此 bind 可实现
_.partial(func, [partials])
类似功能相关问题:
The text was updated successfully, but these errors were encountered: