Misunderstanding Scope in JavaScript?
Posted
by
Jeff
on Programmers
See other posts from Programmers
or by Jeff
Published on 2012-09-18T17:07:08Z
Indexed on
2012/09/18
21:52 UTC
Read the original article
Hit count: 501
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 andarguments
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?
© Programmers or respective owner