手写bind函数
# 手写bind函数
function fn(a, b, c, d) {
console.log(this)
console.log(a, b, c, d);
}
const cb = fn.bind({x: 100}, 1, 2, 3); // {x: 100} 1 2 3 undefined
cb();
// 手写bind
Function.prototype.myBind = function() {
const fn = this;
const arg = Array.prototype.slice.call(arguments);
const _this = arg.shift();
return function() {
return fn.apply(_this, arg);
}
}
const cb2 = fn.bind({x: 100}, 1, 2, 3); // {x: 100} 1 2 3 undefined
cb();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
编辑 (opens new window)
上次更新: 2024/12/19, 09:15:30