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.
var defaultLogger = { |
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.
// Log function defined in the global scope |
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.
// Log function defined externally |
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