JS面试2

箭头函数this指向

1
2
3
4
5
6
7
8
9
10
11
12
class Animal {    
constructor(){
this.type = 'animal'
}
says(say){
setTimeout( () => {
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //animal says hi

当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。并不是因为箭头函数部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。

事件捕获和冒泡

事件捕获 从根元素往目标元素流

事件冒泡 从目标元素往根元素冒

  • 可以用e.stopPropagation()阻止冒泡

利用事件捕获和冒泡的事件流可以实现事件委托

参考文档[‘http://javascript.ruanyifeng.com/dom/event.html']