this
Keyword in JavaScript
The this
keyword in JavaScript depends on the context where it is used:
- Global Context:
- Refers to the global object (
window
in the browser,global
in Node.js).
- Refers to the global object (
- Regular Function:
- Refers to the object that calls the function.
- Arrow Function:
- Defined by the lexical context.
- Classes:
- Refers to the instance of the class.
- Strict Mode:
this
isundefined
in the global context and functions.
- Event Handlers:
- Refers to the element that triggered the event.
Example
function logThis() {
console.log(this);
}
const obj = {
logThis,
logthis2() {
return logThis();
},
logThis3() {
return obj.logThis();
},
};
obj.logThis();
obj.logthis2();
obj.logThis3();