The this
keyword is a pointer which refers to the object it belongs to. In other words, it references the object that is executing the current function. JavaScript this keyword has different values depending on how the code is being executed.
When this is used alone in the global scope, it refers to the window object in the browser or the global object in NodeJs as in the code below,
console.log(this);
// Refers to the window object
Same thing also applies when it is used in a regular function as seen below,
function sayHi() {
console.log(this);
}
sayHi();
//Refers to the window object
Javascript can be tricky sometimes especially with the this keyword, so avoid using arrow functions when declaring a method. It's best to use arrow functions when declaring a function inside a method in an object.
If a function is part of an object, it is called a method. When this is used in a method, it points to the object containing the method and not the window object this time.
// this when used in a method
const obj = {
name: "kaarthik",
hobby: "reading",
sayHi : function () {
console.log(this);
}
};
obj.sayHi(); // {name: "kaarthik", hobby: "reading", sayHi: ƒ}
JavaScript strict mode does not allow default binding. So in a strict mode, this is undefined. In the code below, adding a strict mode "use strict"
will return undefined when you run the code on your console.
function sayHi() {
"use strict";
console.log(this);
}
sayHi(); // undefined