<ul id="list"> <li id="li1">项目一</li> <li>项目二</li> <li>项目三</li> <li>项目四</li> </ul>
const list = document.getElementById(‘list‘) const li1 = document.getElementById(‘li1‘) function addEvent(ele, type, selector, cb) { if (!cb) { cb = selector selector = null } ele.addEventListener(type, function (e) { // e.stopPropagation() const target = e.target if (selector) { if (target.matches(selector)) cb.call(target, e) } else { cb.call(target, e) } }) } addEvent(li1, ‘click‘, function (e) { console.log(1, e.target.innerHTML) console.log(2, this.innerHTML) console.log(this === e.target) }) addEvent(list, ‘click‘, ‘li‘, function (e) { console.log(1, e.target.innerHTML) console.log(2, this.innerHTML) console.log(this === e.target) })
1、this的指向:谁调用就指向谁
2、addEvent定义在window中,调用addEvent时是window调用的,只是window省略不写,其中的this指向window
3、事件函数中this指向事件侦听的DOM对象
4、当addEvent中使用call将cb的this指向target时,再调用addEvent其中的this就指向target了,此时e.target === this
5、以上都是在普通匿名函数中,若使用箭头函数,注意this会指向上一级this