0% completed
The this
keyword is a fundamental concept in JavaScript, providing a way to refer to the context in which the current code is executing. Understanding how this
behaves across different contexts is crucial for mastering JavaScript, especially when working with object-oriented programming and handling events.
In JavaScript, the value of this
is determined by how a function is called. Its value cannot be set by assignment during execution, and it may be different each time the function is called.
this
refers to the global object whether in strict mode or not. In a browser, this
refers to the window
object.this
is bound to the global object, or undefined
in strict mode.this
is bound to the object the method is called on.this
is bound to the newly created object instance.this
context; instead, this
is lexically inherited from the outer function where the arrow function is defined.Explanation:
const person = {...}
):
person
with properties firstName
, lastName
, and a method fullName
.firstName
, lastName
):
fullName
):
this
to correctly refer to the person
object when the method is called.fullName
, this.firstName
accesses the firstName
property of the person
object. Similarly, this.lastName
accesses lastName
.person.fullName()
):
fullName
is called, this
inside fullName
refers to person
, enabling access to the firstName
and lastName
properties. The method returns the concatenated string of these properties.console.log(...)
):
fullName()
method to the console, displaying "John Doe".Explanation:
const person = {...}
):
fullName
is now defined using an arrow function.fullName
):
fullName
is an arrow function, which does not bind its own this
. Therefore, this
inside fullName
does not refer to the person
object but inherits this
from its enclosing execution context (typically global or window in a browser).this.firstName
, this.lastName
):
this
is not bound to person
, this.firstName
and this.lastName
do not point to the properties of person
but to the global context, where these properties are likely undefined.console.log(...)
):
fullName()
method. In a typical browser context without corresponding global variables, this will print undefined undefined
.These examples underscore the importance of understanding the scope and binding of this
in JavaScript, particularly when choosing between function expressions and arrow functions for methods within objects.
this
allows functions within objects to access other properties of the same object, acting as a reference to the object itself.this
provides a direct way to access the object that owns the current executing method......
.....
.....