JavaScript·100 questions

How does this work?

Answer

The keyword this in JavaScript determines the context in which the current code is executing. Its value is dynamically evaluated at the moment the function is called, rather than at the time it is declared. The behavior of this depends on a few clear rules that determine how the function is invoked.

If a function is called as a method of an object, then this points to that object itself. This allows methods to access the properties of their owner. In a regular function called without any context, this refers to the global window object in the browser or to undefined in strict mode, which is often a source of bugs for beginner developers.

Arrow functions behave completely differently. They do not have their own this and inherit its value from the outer lexical context at the time of their creation. This makes them ideal for use inside object methods or callbacks where the context of the outer function needs to be reliably preserved.

When creating an object using the new operator via a constructor function or class, this inside that function refers to the newly created object. Finally, special methods allow you to manage the context manually. By analyzing where a function is called, you can easily determine what this points to in each specific case.

Was this answer helpful?

More questions in this topic

Related questions from other topics