var obj = {
id: '哈哈哈',
cool: function fn() {
console.log('cool:')
console.log(this)
var self = this // 不起作用呀感觉
if (self !== 1) {
console.log('coolSelf:')
console.log(self)
}
},
coolTwo: () => {
console.log('coolTwo:')
console.log(this)
},
coolThree: () => {
console.log('coolThree:')
console.log(this)
},
coolFour: function coolFn() {
console.log('coolFour:')
console.log(this)
setTimeout( function () {
console.log('coolFour:无bind')
console.log(this)
}, 100)
setTimeout( function () {
console.log('coolFour:有bind')
console.log(this)
}.bind(this), 100) // bind this到coolFour环境
},
coolFive: () => { // 只要是箭头函数,你得bind this也会不起作用,还是会动态绑定到执行环境
console.log('coolFive:')
console.log(this)
setTimeout( function () {
console.log('coolFive:无bind 箭头函数下')
console.log(this)
}, 100)
setTimeout( function () {
console.log('coolFive:有bind 箭头函数下')
console.log(this)
}.bind(this), 100)
}
}
var id = '呵呵呵'
obj.cool() // this是obj对象
obj.coolTwo() // this是window,由于=>函数’继承‘了obj.coolTwo函数运行时得this环境绑定 || =>函数之后可以抹杀词法作用域,而实现this动态作用域
obj.coolThree()
obj.coolFour()
obj.coolFive()
setTimeout( obj.cool, 100) // 另一个线程,this是window 测试var self = this也不起作用,不能够绑定this
setTimeout( obj.coolTwo, 100) // 另一个线程,即使没有跳到另一个线程,因为=>函数得存在,this也会指向window
setTimeout( obj.coolThree.bind(this), 100) // bind this到window
效果如下


本文深入探讨JavaScript中箭头函数与bind()方法如何影响this的指向。通过实例解析,揭示它们在不同场景下的应用和区别,帮助开发者更好地理解this的关键概念。
1287

被折叠的 条评论
为什么被折叠?



