Misunderstanding Scope in JavaScript?
- by Jeff
I've seen a few other developers talk about binding scope in JavaScript but it has always seemed to me like this is an inaccurate phrase. The Function.prototype.call and Function.prototype.apply don't pass scope around between two methods; they change the caller of the function - two very different things. For example:
function outer()
{
var item = { foo: 'foo' };
var bar = 'bar';
inner.apply(item, null);
}
function inner()
{
console.log(this.foo); //foo
console.log(bar); //ReferenceError: bar is not defined
}
If the scope of outer was really passed into inner, I would expect that inner would be able to access bar, but it can't. bar was in scope in outer and it is out of scope in inner. Hence, the scope wasn't passed. Even the Mozilla docs don't mention anything about passing scope:
Calls a function with a given this value and arguments provided as an array.
Am I misunderstanding scope or specifically scope as it applies to JavaScript? Or is it these other developers that are misunderstanding it?