I\'ve seen a few other developers talk about binding scope in JavaScript but it
ID: 646297 • Letter: I
Question
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?
Explanation / Answer
You are correct. It's better to think in terms of object context than scope with call and apply. However, this following example might be seen as making a scope accessible to another object context:
function objFactory(){
var someProperty = 'a property of some sort';
this.getSomeProperty = function(){ return someProperty; };
}
var someObj = new objFactory(),
somePlainObj = {};
'a property of some sort' === someObj.getSomeProperty.apply(somePlainObj);//true
I may not have the exact details right but I think JS objects built from function constructors are basically just functions that are copied (along with their scopes - js scopes are function only), executed, and then simply never garbage collect (so all values are persistent) and assigned to a namespace you can access their internally defined properties via altered 'this' rules when you invoke with the 'new' keyword. But the internal vars aren't really private properties exactly (although we tend to think of them that way). They're function constructor properties accessed by the methods via closure.
But the first part of the process is still like a function firing. That makes the internal var accessed via closure which is like a copy of the scope at the moment the constructor was finished with the function execution step.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.