The Different Meanings of this
Here I am creating a few different contexts and naming all of them. So let’s do some testing.
So by default this refers to the global object.
When calling a function this also refers to the global object.
When calling a method this refers to the object the method belongs to.
When using the new keyword to create a new object this refers to the newly created object.
Explicitly setting this
Instead of executing the function here we are using the apply and call methods on Function.prototype. When using these methods the value of this will be set to the first argument passed to the method. This is often used in frameworks so you can reliably use this and know what to expect. Both these methods do the same thing, they just pass arguments in a slightly different way.
So we can even change the value of this for method calls!
There be dragons
Let’s look at two scenarios which can often cause headaches.
So method aliasing doesn’t really work as you expect, but it also means that when we assign a method to an object this will work as expected.
I hope this has been interesting. (C’mon – tell me you didn’t see that coming) Happy coding.