如何自己手动实现 bind , call 和 apply 函数?

手动实现bind 函数

Function.prototype.my_bind= function (context) {
 if (typeof this !== 'function') { // this当然必须为 function 对象
 throw new TypeError('Error')
 }
 let _this = this
 let args = [...arguments].slice(1) // 保存传入的参数,供函数执行时传入
 // 返回一个函数
 return function F() {
 // 因为返回了一个函数,我们可以 new F(),所以需要判断
 if (this instanceof F) {
 return new _this(...args, ...arguments)
 }
 return _this.apply(context, args.concat(...arguments))
 }
}

如何实现一个 call 函数

Function.prototype.my_call = function (context) {
 var context = context || window
 // 给 context 添加一个属性
 context.fn = this
 // 将 context 后面的参数取出来
 var args = [...arguments].slice(1)
 var result = context.fn(...args)
 // 删除 fn
 delete context.fn
 return result
}

如何实现一个 apply 函数

Function.prototype.myApply = function (context) {
 var context = context || window
 context.fn = this
 var result
 // 需要判断是否存储第二个参数
 // 如果存在,就将第二个参数展开
 if (arguments[1]) {
 result = context.fn(...arguments[1])
 } else {
 result = context.fn()
 }
 delete context.fn
 return result
}


分享到:


相關文章: