Function.prototype.myCall = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
// 谁调用call方法,this就指向谁
context.fn = this
// 去掉所有参数中第一参数(指定的对象)
const args = [...arguments].slice(1)
const result = context.fn(...args)
delete context.fn
return result
}
6、手写 apply()
Function.prototype.apply = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
let result
// 处理参数和 call 有区别,apply只有两个参数,第一个是对象,第二个是数组
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
7、手写 bind()
Function.prototype.bind = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this
const args = [...arguments].slice(1)
// 返回一个函数
return function F() {
// 因为返回了一个函数,我们可以 new F(),所以需要判断
if (this instanceof F) {
// 忽略传入的this
return new _this(...args, ...arguments)
}
// 直接调用,将两边的参数拼接起来
return _this.apply(context, args.concat(...arguments))
}
}