Keyword “this”
JavaScript engine every time an execution context is created, that is every time a function is RUN, it gives a variable called “this” pointed to a different object depends on how the function is invoked(where the function is and how it been called)
1 2 3 4 5 6 7 8 9 10 11 |
function greeting(){ console.log(this) } greeting(); // Window var man = { greeting: function(){ console.log(this); } } man.greeting(); // Object { greeting: greeting() } |
Weird part
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var man = { greeting: function(){ function someFunctionSitInObjectFunction(){ console.log(this); } someFunctionSitInObjectFunction(); } } man.greeting(); // Window /* ==== Solution ==== */ var man = { greeting: function(){ var self = this; // by references function someFunctionSitInObjectFunction(){ console.log(self); // look for self variable in scope chain } someFunctionSitInObjectFunction(); } } man.greeting(); // Object { greeting: greeting() } |