Objects, functions, and ‘this’

Execution Context (Creation Phase)

– variable environment
– reference to the outer environment. It will keep stepping outside of its parent environment until it finds what it is looking for.
– ‘this’ variable. Will be pointing to a different object depending on how this function was invoked.

There are a few scenarios which change the ‘this’ variable depending on how the function is called.

Let’s take a look at a couple of these scenarios:

this in standalone functions

In es5, when you create a function, the ‘this’ inside of the function references the global object.

You can crash into the global namespace by using the ‘this’ in es5.

this in literal objects

If the function is attached to an object, the ‘this’ i referencing the object that the function belongs to.

‘this’ of Inner functions of object functions point to global

Now, functions of functions will have it’s ‘this’ pointing to the global object. Thus, when you use ‘this.name’, the this references the global object. You try to access property name which does not exist, so it then adds the name property for you. And assigns it to a literal string “hehe”.

Hence, you have not touched your object c at all. Instead, you’ve manipulated the global object.

There are 3 solutions to this:

Using Function’s prototype methods call

All function object can use prototype methods call, apply, bind.

call invokes the function. It also lets you decide what the ‘this’ variable should be. It let you’s control which Object the ‘this’ inside of the function points to.
‘call’ actually executes the function.

Finally, if you use es6, you can use the arrow function.