call apply bind 改变this指向
call apply bind这三个方法是在前面课程的哪一小节学习过的,我没找到正确的对应位置,老师在本节视频里面说的三者的this指向问题也没有理解
30
收起
正在回答 回答被采纳积分+1
2回答
好帮手慕言
2021-04-19 11:47:39
同学你好,解答如下:
1、call和apply,在之前的课程中有过详细讲解,课程链接:https://class.imooc.com/lesson/1628#mid=39918
使用bind的课程链接:https://class.imooc.com/lesson/1835#mid=41914
2、是不理解老师手动封装的bind1函数吗?如果是的话,可以参考下方:
// 模拟 bind
Function.prototype.bind1 = function() {
// 将参数拆解为数组
// Array.prototype.slice.call()是一个固定的用法,可以将类数组转成数组
const args = Array.prototype.slice.call(arguments)
// 获取 this(数组第一项),就是调用bind1方法时,传递的第一个参数:{x: 100}
const t = args.shift()
// 谁调用函数,函数中的this指向的就是谁,fn1.bind1(...) 这样写,bind1函数中的this指向fn1
const self = this
// 返回一个函数
return function() {
// 调用fn1函数,并把fn1中的this改为{x: 100},此处的args就是10,20,30
return self.apply(t, args)
}
}
function fn1(a, b, c) {
console.log('this', this)
console.log(a, b, c)
return 'this is fn1'
}
const fn2 = fn1.bind1({
x: 100
}, 10, 20, 30)
const res = fn2()
console.log(res)关于this的指向,老师在面向对象的第三章有详细的讲解,同学可以去回顾下,链接:https://class.imooc.com/course/1628
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星