Skip to main content Accessibility Feedback

this sucks

The this keyword in JavaScript is the source of a lot of confusion.

It’s context specific, and changes based on when and where it’s called. Here are some examples.

// logs the window
console.log('global', this);

var logThis = function () {
	// also logs the window
	console.log('logThis', this);
};
logThis();

var LogThis = function () {
	// logs the LogThis() constructor
	console.log('LogThis', this);
};
new LogThis();

var myLibrary = {
	logThis: function () {
		// logs the myLibrary object
		console.log('myLibrary.logThis', this);
	},
	logThis2: () => {
		// logs the window
		// `this` doesn't change its binding in fat arrow functions
		console.log('myLibrary.logThis2', this);
	}
};
myLibrary.logThis();
myLibrary.logThis2();

this sucks

Some developers love this and use it anywhere they can. I think it sucks, and should be avoided whenever possible.

To me, there’s almost always some other variable you can use that’s more clear.

var logThis = function () {
	// The log the same thing, but with the second option,
	// it's immediately obvious what will be logged
	console.log(this);
	console.log(window);
};
logThis();

var myLibrary = {
	logThis: function () {
		// Same here. They both log the same thing.
		// The second choice is much more obvious
		console.log(this);
		console.log(myLibrary);
	}
};
myLibrary.logThis();

In both examples above, using a named variable instead of this makes it far more clear what you’re actually doing.

Should you ever use this?

There is one situation where I do use this, and think it makes sense to do so.

With a constructor pattern, you can instantiate multiple instances of your constructor, each with its own properties and values.

The this keyword represents the current instantiation, and is the best choice for accurately using that instance’s unique properties and values.

var sayHi = function (greeting) {
	this.greeting = greeting;
};

sayHi.prototype.greet = function () {
	alert(this.greeting);
};

var hi = new sayHi('Hi there!');
var aloha = new sayHi('Aloha');

hi.greet();

Here’s the constructor in action.