Understanding Javascript’s this

I was recently asked what this means while reviewing some toy javascript problems.

There are a few different contexts for this and it is important to review them all, but for the shortest answer, this refers to the element that is executing the code.

This can mean different things depending on the context.

Global Context – Within the global scope, this refers to the global object and in most cases this is the window object.

console.log(this === window); // true
foo = "bar";
console.log(this.foo); // bar

Function Context – Within simple functions calls, this refers to the object that the function is running on. If the function exists in the global scope, then this refers to the window/global object.

function func() { console.log(this); }
func(); // within the browser = window | within node = global

If the function is nested within another scope/object or run with bind(object) , then this refers to the object executing the function.

var testObj = {
name: "foo",
whatIsThis: function() {
testObj.whatIsThis(); // {name: "foo"; whatIsThis: f}

.. to be continued