DEV Community

Discussion on: 🧐Most Confusing Part Of JavaScript.

Collapse
 
peerreynders profile image
peerreynders • Edited

➡️ this has a different values depending on where it is used.

No. For a regular function it depends on how it's invoked - not where it is used. For arrow and bound functions 'this' is fixed permanently.

➡️ Inside a method this refers to the owner object.

Only when called through the object reference either with dot notation obj.fn or index notation obj['fn']. A function isn't owned - it can merely be used in the manner of a method. Unless you are using arrow or bound functions explicitly, objects constructed via class still use regular functions as methods to facilitate implementation inheritance. For regular functions 'this' is bound dynamically at runtime when the function is invoked. So the same function instance can see different values of 'this' during its lifetime just like any of its other arguments can vary from one invocation to the next.

➡️ In a event this refers to the element that received the event.

This is only true in React when a regular function is bound in the constructor or render or with an arrow function (automatically bound to the object inside the constructor or the render function). Function expressions (regular or arrow) created inside functional components use the references returned by hooks (instead of 'this') to reference data inside the closures that React is managing on the component's behalf.

React's synthetic event system didn't bother implementing event-handling-by-object as it is implemented in the DOM via the EventListener.handleEvent() method. In his usual enterprising manner Andrea Giammarchi (WebReflection) found a way around that.

With regular DOM events Event.target is the element on which the event occurred while Event.currentTarget identifies the current target element for the event as the it traverses the DOM during the event bubbling or capturing phase.