实现一个bind

简易版

1
2
3
Function.prototype.myBind = function (obj, ...args) {
return (...rest) => this.call(obj, ...args, ...rest);
};

使用示例

1
2
3
4
5
6
7
8
9
function f(arg) {
console.log(this.a, arg);
}

// output: 3, 4
f.bind({ a: 3 })(4);

// output: 3, 4
f.myBind({ a: 3 })(4);

《JavaScript 权威指南》实现 bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)
}
}
}