手写一个bind函数

call、apply、bind这些都是Function.prototype中定义的。我们将手写的bind1直接写到Function的原型上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 模拟 bind
Function.prototype.bind1 = function () {
// 将参数拆解为数组
const args = Array.prototype.slice.call(arguments)

// 获取 this(数组第一项)
// args.shift()删去并返回原args[0]
const t = args.shift()

// fn1.bind(...) 中的 fn1
const self = this

// 返回一个函数
return function () {
return self.apply(t, args)
}
}

function fn1(a, b, c) {
console.log('this', this)
console.log(a, b, c)
return 'this is fn1'
}

const fn2 = fn1.bind1({x: 100}, 10, 20, 30)
const res = fn2()
console.log(res)