apply、call、bind
区别
执行时机 | 参数传参 | 改变this指向 | |
---|---|---|---|
apply | 直接执行 | 第二个参数是数组或类数组 | 可以 |
call | 直接执行 | 一个一个传 | 可以 |
bind | 调用的时候 | 一个一个传 | 可以 |
使用bind\call\apply
let obj1 = {
grade: 'B',
sayName: function(name = 'obj1', age = '10000') {
console.log(`我是${name},今年${age}岁, 成绩:${this.grade}`)
}
}
let obj2 = {
grade: 'A',
}
obj1.sayName()
obj1.sayName.apply(obj2, ['obj2', '18'])
obj1.sayName.call(obj2, 'obj2', '18')
obj1.sayName.bind(obj2, 'obj2', '18')()
动手实现
Function.prototype.apply = function(context){
context = context || window
let args = arguments[1] || []
context.fn = this
let res = context.fn(...args)
delete context.fn //删除context多余fn
return res
}
obj1.sayName.apply1(obj2, ['obj2', '18']) //我是obj2,今年18岁, 成绩:A
//call 和 bind是包装在apply上的语法糖
Function.prototype.call1 = function (context) {
let argu = []
for(let i = 1; i < arguments.length; i++) {
argu.push(arguments[i])
}
this.apply1(context, argu)
}
obj1.sayName.call1(obj2, 'obj2', '18')//我是obj2,今年18岁, 成绩:A
Function.prototype.bind1 = function (context) {
let self = this
let arr = Array.prototype.slice.call(arguments, 1);
return function() {
let new_arr = Array.prototype.slice.call(arguments);
return self.apply(context, arr.concat(new_arr))
}
}
obj1.sayName.bind1(obj2, 'obj2', '18')(1,2)//我是obj2,今年18岁, 成绩:A
参考链接:
5分钟带你搞懂 Javascript 中的this(包含apply、call、bind) - 掘金 (juejin.cn)