3. Execution Context and this
-
Question: Explain how it works and how the value of
this
is determined in different scenarios.-
this
refers to the object of the context, and its value depends on how a function is called:- In the global context, outside of any function:
this
refers to the global object (e.g.,window
in the browser). - Inside a method:
this
refers to the object that owns the method. - In DOM events:
this
refers to the element that triggered the event. - With
call
,apply
, orbind
: you can explicitly set the value ofthis
.
- In the global context, outside of any function:
-
Examples:
- Global Context
console.log(this); // In the browser, this will log the global object `window`
- Inside a Method
const person = {
name: 'John',
greet: function() {
console.log(this.name); // `this` refers to the `person` object
}
};
person.greet(); // Output: John
- In DOM Events
<button id="myButton">Click me</button>
<script>
document.getElementById('myButton').addEventListener('click', function() {
console.log(this); // `this` refers to the button element that triggered the event
});
</script>
-
Using
call
,apply
, orbind
function greet() {
console.log(`Hello, ${this.name}`);
}
const person = { name: 'Jane' };
greet.call(person); // Output: Hello, Jane
greet.apply(person); // Output: Hello, Jane
const boundGreet = greet.bind(person);
boundGreet(); // Output: Hello, Jane
Top comments (0)