事件绑定中 this 的指向问题

html 代码:

<div class="container">
    <div id="aa" onclick="clicke()"></div>
</div>
1. 在 element 上绑定事件

此时 this 指向 全局变量

function clicke() {
  	console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
}
2. js 绑定 onclick 事件

此时的 this 指向 该元素

document.getElementById('aa').onclick = function () {
	console.log(this);  //  <div id="aa"></div>
}
3. js 使用 addEventListener 绑定事件

此时的 this 指向 该元素, 注意: 在IE浏览器中,使用为 attachEvent(), this 指向全局变量

document.getElementById('aa').addEventListener('click', function () {
	console.log(this);  //  <div id="aa"></div>
});
4. jquery 的 3种绑定 click 事件

此时的 this 均指向该元素

$('#aa').bind('click', function () {
    console.log(this); //  <div id="aa"></div>
})

$('#aa').click(function() {
    console.log(this); //  <div id="aa"></div>
})

$('#aa').on('click', function () {
    console.log(this); //  <div id="aa"></div>
})

注意: 在 ES6 箭头函数中,this 指向当前函数作用域的上层。在这里 即指向 全局
写个小例子:

var demo = function () {
    this.a = 'demo';
    this.c = {
        a: 'c',
        b: () => {return this.a},
        d: function () {return this.a}
    }
}

console.log(new demo().c.b()); // demo
console.log(new demo().c.d()); // c

jquery 具体代码:

$('#aa').bind('click', () => {
    console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
})

$('#aa').click(() => {
    console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
})

$('#aa').on('click', () => {
    console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
})
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值