What is scope?
In computer programming, scope is an enclosing context where values and expressions are associated.
Also note that if you define a variable in a nested scope that has the same name as an outer scope the variable will reference in the inner most scope. As seen here.
Whats with the var?
The var keyword is used to say this variable belongs to the current scope. Without using this keyword in a function the variable will be put into the global scope. To see this in action see the following code sample.
Where did the global scope come from?
As you can see when you do not define a variable with var then your variable will end up in the global scope which can then be referenced outside of your function with or without referencing the name of the global scope.
When we use the var keyword we are actually putting variables in the local scope. This scope is only accessible to itself and nested functions. See this code sample:
As you can see the variable created with the var keyword is not accessible outside of the function. On the other hand you can use the this keyword. The this keyword is used to reference the current execution context and will be available as a public variable as seen here.
However one of the most important features of the this keyword is the fact that you can change the current execution context. The are 3 ways to change the current execution context: call, apply, bind. These are often used to change execution context when executing a callback. Take a look at the following:
As you can see if you do not use call,apply or bind then this in the callback will not reference the button firing the event. To make this work you can do the following. Using call you can pass in this as the first parameter and then a list of the arguments to the function. This will set this of the callback function to the this that is passed into the call function.
Alternatively you could use apply. The only difference is the arguments that are passed to the function are defined as an array. As seen here: . Lastly there is bind which returns a copy of the function with this and the arguments bound which you can then call later.