// call实现
Function.prototype.callFun = function(obj, ...args) {
if (!obj) {
obj = typeof window === 'undefined' ? global : window
}
obj.func = this
let res = obj.func(...args)
delete obj.func
return res
}
// apply实现
Function.prototype.applyFun = function(obj, args) {
if (!obj) {
obj = typeof window === 'undefined' ? global : window
}
obj.func = this
let res = obj.func(...args)
delete obj.func
return res
}
// bind实现
Function.prototype.bindFun = function(obj, ...args) {
let _this = this
if (!obj) {
obj = typeof window === 'undefined' ? global : window
}
return function() {
_this.call(obj, ...args, ...arguments)
}
}
var name = 'aaa'
var obj = { name: 'bbb' }
function a(age, job) {
console.log(this.name, '我今年' + age + '岁', '我的工作是' + job)
}
let funs = a.bindFun(obj, 20)
funs('敲代码')
原理:
首先是函数调用,所以在Function类的原型上添加这个方法,首先判断第一个参数存不存在,不存在判断是否在window环境下,
主要是给第一个参数添加一个随机属性值为this,该this指向调用这个方法的fun,此时再调用这个对象,的这个方法,方法就会指向这个绑定对象,拿到返回值后,删掉随机对象,返回调用后结果