# js 中如何实现 bind
更多描述
提供以下测试用例,注意第二条测试用例,因此 bind 可实现 _.partial(func, [partials])
类似功能
function f(b) {
console.log(this.a, b);
}
//=> 3, 4
f.fakeBind({ a: 3 })(4);
//=> 3, 10
f.fakeBind({ a: 3 }, 10)(11);
相关问题:
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 32 (opens new window)
Author
最简单的 bind
一行就可以实现,而在实际面试过程中也不会考察你太多的边界条件
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);
Author
那我再抄一个加强版吧嘻嘻 《JavaScript 权威指南》P191 ES3 实现 bind
if (!Function.prototype.bind) {
Function.prototype.bind = function(o /*, args */) {
var self = this, boundArgs = arguments;
return function () {
var i, args = [];
for (i = 1; i < boundArgs.length; i++) {
args.push(boundArgs[i])
}
for (i = 0; i < arguments.length; i++) {
args.push(arguments[i])
}
return self.apply(o, args)
}
}
}