箭头函数
箭头函数没有 this,若在里面使用 this,则指向上下文对象。
普通函数
非严格模式
this === window
严格模式
this === undefined
对象中的方法
自然是指向对象
apply/call/bind
改变this指针,也可以理解为对象借用方法,就现像生活中向邻居借东西一样的事情。
bind
bind()是将函数绑定到某个对象,比如 a.bind(hd) 可以理解为将a函数绑定到hd对象上即 hd.a()
- 与 call/apply 不同bind不会立即执行
- bind 是复制函数形为会返回新函数
事件监听器中的 this
普通方式添加监听器
this 指向 dom
handleEvent
使用handleEvent绑定事件处理器时,this指向当前对象而不是DOM元素。
<button>button</button> <script> let Dom = { site: "后盾人", handleEvent: function(event) { console.log(this); }, bind() { const button = document.querySelector("button"); button.addEventListener("click", this); } }; Dom.bind(); </script>
参考
http://houdunren.gitee.io/note/js/8%20%E5%87%BD%E6%95%B0%E8%BF%9B%E9%98%B6.html#this