This article takes a closer look at what is called method context in JavaScript.

Method context refers to the way the this keyword behaves inside a function. It is different in JavaScript than in other languages. As we are going to demonstrate here, the value of this is determined by how and where a function is called.

Function defined and called as an object method

The simplest scenario is a function defined and called as an object method. In that case, this is set to the object the method is called on.

1
2
3
4
5
6
7
8
var defaultLogger = {
loggerName: "Default",
log: function log(message) {
console.log("[" + this.loggerName + "] " + message);
}
};

defaultLogger.log("example 1"); // logs "[Default] example 1"

In the log function here, this corresponds to defaultLogger.

Function defined in the global scope

By extension, if a function is defined in the global scope. this will be set to window (global object) when the code is executed in the browser.

1
2
3
4
5
6
7
8
9
10
// Log function defined in the global scope
function log(message) {

console.log("this " + this);
var loggerName = this.loggerName || "Default";

console.log("[" + loggerName + "] " + message);
}

log("example 2"); // Logs "this: [object Window]" then "[Default] example 2"

Because the function is defined and executed in the global scope, in the log function here, this points to the global window object.

this.loggerName is then undefined and the "Default" logger name is used instead.

Function defined in the global scope and used as an object method

We can reuse the function defined above and use it in the context of an object. In that case, this will point to that object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Log function defined externally
function log(message) {

console.log("this: " + this);
var loggerName = this.loggerName || "Default";

console.log("[" + loggerName + "] " + message);
}

// Using the log function in the context of an object
var databaseLogger = {
loggerName: "Database",
log: log
};

databaseLogger.log("example 3"); // Logs "this: [object Object]" then "[Database] example 3"

Because we are calling the log function with the dot notation (databaseLogger.log()), the context is set to the object.

In conclusion, it does not matter where the function is defined; the context depends on which object the function is invoked from.

Check out the code here: https://jsbin.com/ciqolu/edit?js,console