Yes! You read it right. This is not that in Javascript and otherwise.
The this keyword in javascript can be confusing for a naive JS learner. Its behaviour varies depending on the execution context. In general, this refers to the object under current execution.
- this, when used alone refers to a global object.
var a = this;
console.log(x);
A browser window
- this, when used in an object method, refers to owner of the object method.
var car = {
model: BMW,
colour: black,
details: function(){
return this.model + " " + this.colour;
}
};
this refers to the car object. The car object is owner of its properties and methods.
console.log(car.details());
BMW black
- this, when used in a function refers to a global object
function testFunction() {
return this;
}
returns the global object [object Window]
. However, in strict mode, the above testFuntion returns undefined
- this, when used in event handling
refers to the html DOM element on which the event listener is placed
Click here!
alerts with button tag name.