thiskeyword to refer to the instance of the class. E.g., consider this case:
thisrefers to an instance of the
Toppingsclass. As long as the
listmethod is called using dot notation, like
formatToppings()method defined on the instance of the class. This will also ensure that inside
thisrefers to the same instance.
thiscan also refer to other things. There are two basic cases that you should remember.
someMethodwill refer to
someObject, which is usually what you want.
someFunctioncan refer to different things depending on whether we are in "strict" mode or not. Without using the "strict" mode,
thisrefers to the context in which
someFunction()was called. This is rarely what you want, and it can be confusing when
thisis not what you were expecting, because of where the function was called from. In "strict" mode,
thiswould be undefined, which is slightly less confusing.
thisto refer to
console, but the reference was lost when the function was detached from
thisexplicitly. One way to do this is by using
bind()method, which allows you to specify the value to use for
thisinside the bound function.
Function.apply, but we won't discuss this here.
thiscan be confusing is with respect to anonymous functions, or functions declared within other functions. Consider the following:
thiswill not point to the expected object: in "strict" mode it will be
undefined. This leads to another ES6 feature - arrow functions, which will be covered next.