手撕源码

实现 call()、apply、bind()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// call
Function.prototype.call = function call(context, ...args) {
const self = this
const key = Symbol('key')
// null undefined
context == null ? (context = window) : null
// string number
!/^(object|function)$/i.test(typeof context) ? (context = Object(context)) : null

// array function object
context[key] = self
const result = context[key](...args)
delete context[key]
return result
}

// bind
Function.prototype.bind = function (context, ...args) {
const _this = this
return function proxy(...params) {
return _this.apply(context, args.concat(params))
}
}