Lesson 12 of 55 · javascript
The `this` Keyword – Binding Rules
Duration: 12 mins
How this is set depends on call site:
- Function call –
thisisundefinedin strict mode, otherwise the global object. - Method call –
obj.method()→thisisobj. - Constructor (
new) –thisis the newly created object. - Arrow function –
thisis lexically inherited from the surrounding scope. - Event listeners –
thispoints to the element the listener is attached to (unless an arrow function is used).
Example: Arrow vs normal function in an event listener
const btn = document.querySelector('button');
btn.addEventListener('click', function(){ console.log(this); }); // logs <button>
btn.addEventListener('click', () => { console.log(this); }); // logs Window (lexical this)