this — most confused mechanism in Javascript
This is the part 1 of the series on this keyword in Javascript
Well, what is this keyword in Javascript?
Special identifier keyword that’s automatically defined in scope of every function. However this doesn’t in anyway refer to function’s lexical scope. Internally, scope is like an object with properties for all available identifiers. Scope object is not accessible to JS code. It’s inner part of engine’s implementation.
function useThis() {var a = 2;this.useVariable();}function useVariable(){console.log(this.a);}useThis();//ReferenceError: a is not defined
What’s this ?
this binding is associated with the manner in which the function is called. When a function is invoked, an activation record, otherwise known as an execution context is created and it contains info about where the function was called from(call stack) , how the function was invoked, what parameters were passed, etc. It also contains information about this reference which will be used during function execution.
Part 2: Call Site