Difference between scope and context in JavaScript
Difference is scope is function based and context is object based.
Scope
Variables can have either local or global scope. Local variables exist only within the function in which they are defined. Variable declared outside the function can be accessed and modified by another function also.
var planet = "sun"; // global variable
console.log(planet); //sun
function solar_system() {
var star = "sun"; // local variable
}
console.log(star); // Error, star is not defined
Context
Context this
is set to the object the function is called on.
var myObj = {
id: 10,
myFunc: function() {
console.log(this.id); // this refers to `myObj`
}
};
myObj.myFunc(); // 10
function foo() {
console.log(this); // `this` refers to the `window` object
}
foo();
Reference
Categories :
JavaScript