this
keyword in JavaScript is used to refer to the object, that owns the function being called.In case of a standalone function, that is not part of any object, this
refers to the root object, which is Window
:
function test() {
console.log(this.toString());
}
test(); // [object Window]
In case of a method, this
refers to the owning object:
const object = {
test: function() {
console.log(this.toString());
},
getThis: function() {
return this;
}
};
// [object Object]
object.test();
// true
console.log(object.getThis() === object);