手写call、apply、bind
区别&联系
三者都是指定函数执行时的上下文,第一个参数都是上下文;
call从第二个参数开始,后续所有的参数传递给函数执行;
apply第二个参数是一个数组,传递给函数执行;
bind返回一个指定上下文的方法,等待后续执行。
实现:
Function.prototype._call = function(ctx = window, ...args) {
ctx.fn = this
const result = ctx.fn(...args)
delete ctx.fn
return result
}
Function.prototype._apply = function(ctx = window, args) {
ctx.fn = this
const result = ctx.fn(...args)
delete ctx.fn
return result
}
Function.prototype._bind = function(ctx = window) {
const _this = this
ctx.fn = this
return function F(...args2) {
// 判断是否用于构造函数
if (this instanceof F) {
return new _this(...args1, ...args2)
}
return _this.apply(context, args1.concat(args2))
}
}
const fn = function(...args) {
console.log(this.name, args)
}
const obj = {
name: 'obj'
}
fn._call(obj, 1, 2, 3)
fn._apply(obj, [1, 2, 3])
fn._bind(obj)(1, 2, 3)
存在的问题
1.如果传入的ctx(上下文环境)不是Object类型,则需要将其替换成对应的包装类型;
2.直接给传入的ctx增加一个fn,然后用delete去删除是否不太好?