btn.onclick = function () {
console.log(this) //指向的是调用者btn
}
const user = {
name: ‘Jack‘
}
btn.onclick = (function () {
console.log(this) //指向user
}).call(user)
this即为当前对象
const zhangsan = {
name:‘张三‘,
sayHi(){
console.log(this)//{ name: ‘张三‘, sayHi: [Function: sayHi] }
console.log(this.name)//张三
}
}
constructor里面的this指向创建的实例
函数里的this指向的是调用者
btn.onclick = () => {
console.log(this) //指向window
}
注意哦,setTimeout实际为window.setTimeout,所以左图this指向window。而右图使用了箭头函数,this指向函数定义时所在的对象
addEventListener()
事件处理程序会在其所属元素的作用域内运行,但当用了箭头函数则会导致里面的this指向改变。因此不建议在创建事件的时候搭配箭头函数使用
还需注意:另一种添加事件的方法attachEvent
IE事件处理程序会在全局作用域中运行,因此this = window。
p2.addEventListener(‘click‘,?function?()?{
????console.log(this)?????//p2元素
})
p2.addEventListener(‘click‘,?event?=>?{
????console.log(this)????//window
})
function bindEvent(element, type, selector, fn) {
if (fn == null) { //避免不用代理时传element,type,fn
fn = selector
selector = null
}
console.log(this) //window
//这里箭头函数this指向的是函数bindEvent的作用域中的this,也就是window
element.addEventListener(type, event => {
const target = event.target
console.log(this) //window
if (selector) {
// 代理
if (target.matches(selector)) { //符合选择器
fn.call(target, event) //将fn的this值绑定到target中
}
} else {
//普通
fn.call(target, event)
}
})
}
bindEvent(p1, ‘click‘, function () {
console.log(‘参数‘,this) //这里的this指向用call改变过,指向target(这里是p1)
})
注意:上面调用函数bindEvent
的时候,参数三不可以写成箭头函数的形式,因为箭头函数的this指向固定不可变(也就是说用bind、apply、call都无法改变,字面意思就是固定不变)
原文:https://www.cnblogs.com/L-xmin/p/12893863.html