this. Its value depends on where it is used and how that function is called.
this in a constructor#
We saw previously that a
constructor in a
class is a special method which is used to instantiate on a new object. When used inside a
this refers to the new object being created.
this in a method#
A method is a function that belongs to an object. That object can be either be created as an object literal or using a class.
In both above example
sayHi is a method which belong to
When a method is called, the value of
this inside of that method will be the object that the method belongs to. In the example above that will be
this in a function#
The value of
this in a standalone function if it's executed in the browser will be the
window object. If it is executed in Node it will be the
We can take a method and assign it to a variable. Essentially that turns it from being a method into a standalone function.
In above example, we are executing
sayHi as a function, not method. As a result we no longer have access to the object the method belongs to. That results in the value of
this being lost and instead of being
person it is now
That can be a problem. Fortunately we can fix it
this inside it is bound to the object it belongs to. That allows us to call methods as functions without losing the value of
this inside it.
This behaviour will become important in the near future, when we will need to start passing methods to be called other parts of our code.
In break out groups solve the following exercises. Only run code to verify answers. Try to understand what each line of code is doing and the effect it has.