JavaScript what is “this”
“this” in js functions
I am getting deeper into the JS rabbit hole and as a programmer with more experience with strongly typed languages I find some things hard to grasp in languages where functions are first class elements (learn more here). One thing that is not tricky but interesting is the different values for “this” in a function. What “this” is in a function depends on how it is used. These are my brief notes about functions and “this”, feel free to comment if you see something incorrect.
As a global function: honk();
- this = global context(window object)
As a method: myCar.honk()
- this = object that method belongs to
As a constructor: new Car()
- A new empty object is passed to function as this parameter
- This happens because of the new keyword is used before the function call
Function called with honk.apply(…) or honk.call(…)
- Here you can decide what “this” is, because it is passed into the call to apply and call
- apply(object(will be this), [array of params]);
- call(object(will be this), param, param….);
Examples with console output
Console output for above code
June 11, 2012 | Filed Under JavaScript | Leave a Comment