Back to Posts

Javascript 'This'

We use this similar to the way we use pronouns in natural languages like English and French. We write, “John is running fast because he is trying to catch the train.” Here is a helpful writeup on Javascript’s This.

All functions in JavaScript have properties, just as objects have properties. And when a function executes, it gets the this property—a variable with the value of the object that invokes the function where this is used. Here’s an example:

var person = {
	firstName: "John",
	lastName: "Brown",

	// Since the "this" keyword is used inside the 
	// showFullName method below, and the showFullName 
	// method is defined on the person object,
	//"this" will have the value of the person object 
	// because the person object will invoke showFullName()​

	showFullName:function () {
		console.log (this.firstName + " " + this.lastName);
	}	
​
}
​
person.showFullName (); //John Brown


In most cases, the value of this is determined by how a function is called. It can’t be set by assignment during execution, and it may be different each time the function is called. It is important to understand that in JavaScript, this is not assigned a value until an object invokes the function where this is defined.