call/apply/bind
2019-02-23 本文已影响0人
jiangzj
// func.geCall(obj, 'arg1', 'arg2')
Function.prototype.geCall = 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
}
// func.geApply(obj, ['arg1', 'arg2'])
Function.prototype.geApply = 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
}
Function.prototype.geBind = function(context){
let _this = this
let args = [...arguments].slice(1)
const fn = function() {
return _this.apply(context, [...args, ...arguments])
}
return fn
}