It is often to use
this will behave differently.
On normal condition, calling
this will return global object. Look at example below:
As we can see above, we can access global object via
this operator even though it is inside a function scope. However if we set
use strict on the beginning of the function body,
this operator will not refer to global object because currently it has a different context than outside of the function.
this to be a certain object just like what we have on
In example above,
this operator is referring to
body’s DOM object which has been attached to an event handler. But we can also change
this so it refers to an object that we define ourselves. Suppose instead of changing
body background color, we want the
h1 to change its background color when a user clicks
bind, we can apply the value of
this according to the object which we input as parameter. Aside from
bind, we can also use
apply function. The difference is when
apply is called, the corresponding function will be run.
There is a difference between
apply when inserting function’s parameters. In
call case, it accepts parameter explicitly, whereas
apply accepts parameter in array form.
In previous articles i had explained about module pattern. By using
this inside of a method, we can call object’s methods or properties on the same module just like what the examples is shown below.
this is indeed tricky, especially when it is used outside module pattern. Please always add