Below content is an excerpt from my book – “JavaScript for C# developers“.
As with many things in javascript, the evaluation of the value of ‘this’ keyword in JavaScript is completely different from how it is done in C#. Before discussing about how JS engine evaluates the value of ‘this’ keyword in javascript, let us revisit how ‘this’ works in C#.
Consider the below C# code snippet, where we have created couple of instances of Employee class. We are calling ‘PrintName’ method using these instances. So, whenever you use ‘this’ keyword inside a class, it would always point to the object using which the method is called with.
In the above code, we’re calling PrintName method using objects ‘e1’ and ‘e2’ and thus the value of ‘this’ would be ‘e1’ and ‘e2’ object at line 25 and 26 respectively.
‘this’ in javascript:
Value of ‘this‘ keyword in javascript is evaluated at runtime based on how a function is called. We would discuss various scenarios on how the value of ‘this’ is evaluated.
1. Invocation of function through object
Consider below code snippet where we’ve declared couple of objects – obj1 and obj2. Both objects have name, age and printName properties. As discussed in ‘Chapter 3 – Functions’, functions are reference types and thus there will not be multiple copies of the function. Both objects ‘obj1’ and ‘obj2’ have references which point to the same function.
When you call the function ‘printName’ using object ‘obj1’ as in line no 17, the value of ‘this’ keyword would be object ‘obj1’. At line 18, the value of ‘this’ keyword would be object ‘obj2’ as using that object only the function was called.
2. Invocation of function directly (without any object)
Below code snippet is similar to the previous code snippet with few changes. At. line 18, we have declared a variable fn whose value is the reference to the function ‘printName’ defined in object ‘obj1’. And, at line no 19, we’ve declared a variable ‘name’ in global scope whose value is “Global”.
At line 21, we’re calling the function directly and not through any object.
If you’re calling a function directly, the value of ‘this’ would be global object in non-strict mode and undefined in strict mode. As we’re running the code in the browser, the global object is the window object provided by the browser.
As we are running the above code in non-strict mode, the above code snippet would print “Global”.
In the next blog post, we would discuss how value of ‘this’ would be evaluated in below scenarios.
- Invocation of function with either call or apply
- Invocation of function when bind is used
Please let me know your thoughts in comments.