What is the difference between Scope and Context in JavaScript ?
A context of a function is the value of this
for that specific function.
A Scope on the other hand defines the way javascript resolves a variable at run time. There are four scopes in JavaScript.
- global
- function
- block
- module
I also deals with scope chain
that makes closure possible.
In simple words we can say, When a piece of code is running scope
of variable decides what variable do i have access to and context
is the value of this
.
In Details
Below is an example of object context.
<button id="ok">
Ok Button Clicked <span>0</span> times
</button>
<ul id="ul">
<li>li 1 Clicked <span>0</span> times</li>
<li>li 2 Clicked <span>0</span> times</li>
<li>li 3 Clicked <span>0</span> times</li>
<li>li 4 Clicked <span>0</span> times</li>
<li>li 5 Clicked <span>0</span> times</li>
</ul>
var obj = {
foo : function(){
console.log(this);
this.querySelector('span').innerText = parseInt(this.querySelector('span').innerText) + 1
}
}
document.querySelectorAll('button').forEach(x => x.addEventListener("click",obj.foo));
document.querySelectorAll('li').forEach(x => x.addEventListener("click",obj.foo));
clicking on button
will change the inner value of span
by 1 each time. Similarly clicking on li
will change the value of span
with in li
by 1 each time.
tip
Note : To know more about scope please refer :