Methods And “This”
A method of an object is a property containing a function definition. Within methods you can often use “this” in order to implicitly reference the proper context object that owns the function: this
can be used in any function, allowing you to re-use that same function for different objects without having to change its specifics. The value of this
can be anything, and its binding is made for each function invocation depending on its call-site.
For instance:
let firstObject = { a: x, funct: function() { return this.a } };
let secondObject = { a: y, funct: function() { return this.a } };
In the first case this.a
will represent firstObject.a
, whereas in the second case it will represent secondObject.a
. In other words, this.property
is a simple way to consider a specific property of the object containing the function (object.property
).
Arrow functions, however, are an exception, as they discard all the normal rules for the binding of this
. When using this
with arrow functions, you always have to keep in mind that its value is going to be inherited by the function’s immediate lexical enclosing scope (or, in other words, its parent element).
In the browser, the value of this
in the global area is window
.